如何防止 link 单击事件传播?

How do I prevent event propagation on link click?

当我点击 a-tag 时,我不想触发 parent 的事件。如果 child 有一个正常的事件监听器,它可以通过 event.stopPropagation() 来阻止,但是当没有 "event" 时我该怎么办?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="parent" style="width:100px; height:100px; background-color: red">
    <a id="child" href="https://i.kym-cdn.com/entries/icons/facebook/000/013/564/doge.jpg">Text</a>
</div>
<script>
    document.getElementById("parent").addEventListener("click", function () {
        alert("Oh no, you clicked me!");
    });
</script>
<script src="test.js"></script>
</body>
</html>

方法一

If the child had a normal event listener, it could be prevented by event.stopPropagation()

是的。

but how do I do it when there is no "event"?

有活动。你只是没有在听它。

您可以通过监听子元素来解决问题:

document.getElementById("parent").addEventListener("click", function() {
  alert("Oh no, you clicked me!");
});

document.querySelector("a").addEventListener("click", function(e) {
  e.stopPropagation();
});
<div id="parent" style="width:100px; height:100px; padding: 1em; background-color: #aaa">
  <a id="child" href="https://placeimg.com/200/200/nature/sepia">Text</a>
</div>


方法二

或者,您可以检查事件的 target,看看它是否不可接受。

const blacklist = [document.querySelector("a")];

document.getElementById("parent").addEventListener("click", function(e) {
  if (blacklist.includes(e.target)) {
    return;
  }
  alert("Oh no, you clicked me!");
});
<div id="parent" style="width:100px; height:100px; padding: 1em; background-color: #aaa">
  <a id="child" href="https://placeimg.com/200/200/nature/sepia">Text</a>
</div>

只需将点击侦听器添加到 link,然后在 event.stopPropagation(); 上执行。这将防止点击子项冒泡(从而触发对父项的点击)。

document.getElementById("parent").addEventListener("click", function() {
  console.log('parent received click');
});

document.getElementById("child").addEventListener("click", function(e) {
  e.preventDefault(); // this line prevents changing to the URL of the link href
  e.stopPropagation(); // this line prevents the link click from bubbling
  console.log('child clicked');
});
<div id="parent" style="width:100px; height:100px; background-color: red">
  <a id="child" href="https://i.kym-cdn.com/entries/icons/facebook/000/013/564/doge.jpg">Text</a>
</div>
<script>
</script>

试试这个。

document.getElementById(id-here).addEventListener("click", function(e) {
  e.stopImmediatePropagation();
  console.log("clicked");
});

根据我的经验,调用 event.stopImmediatePropagation(); 会给你预期的结果。

event 对象在 onclick 处理程序中也可用:

<a id="child" href="https://i.kym-cdn.com/entries/icons/facebook/000/013/564/doge.jpg"
  onclick="event.stopPropagation()">Text</a>

灵感来自 this.

⚠️ 与 Internet Explorer 不兼容,但与 Edge 兼容(已在 v89 上测试)。