代码之家  ›  专栏  ›  技术社区  ›  user13286

让锚点元素上的点击事件监听器也应用于锚点的子元素[重复]

  •  0
  • user13286  · 技术社区  · 3 年前

    我正在使用 click 事件监听器在我的锚点上,但锚点内部也有一个跨度,如果你点击锚点内的跨度,事件监听器就不会工作。

    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('external-link')) {
        e.preventDefault();
        console.log('button clicked');
      }
    });
    a {
      background: blue;
      color: white;
      display: flex;
      flex-wrap: wrap;
      width: 200px;
      height: 40px;
      font-weight: bold;
      line-height: 20px;
      align-items: center;
      justify-content: center;
      text-align: center;
      text-decoration: none;
    }
    
    a span {
      display: block;
      width: 100%;
      font-weight: normal;
      font-style: italic;
    }
    <a href="#" class="external-link">Click Me <span>(External)</span>

    如何调整我的事件侦听器,使其触发锚点单击,无论您单击锚点的哪个位置?

    1 回复  |  直到 3 年前
        1
  •  3
  •   epascarello    3 年前

    目标是你点击的内容,所以当你点击锚点时,它是子对象,而不是锚点。不会为链上的每个元素触发该事件。

    因此,您需要遍历链并检查元素。你可以用 closest()

    document.addEventListener('click', function(e) {
      const externalAnchor = e.target.closest('a.external-link');
      if (externalAnchor) {
        console.log('here');
        e.preventDefault();
      }
    });
    a {
      background: blue;
      color: white;
      display: flex;
      flex-wrap: wrap;
      width: 200px;
      height: 40px;
      font-weight: bold;
      line-height: 20px;
      align-items: center;
      justify-content: center;
      text-align: center;
      text-decoration: none;
    }
    
    a span {
      display: block;
      width: 100%;
      font-weight: normal;
      font-style: italic;
    }
    <a href="#" class="external-link">Click Me <span>(External)</span>