当我点击我的 a 标签时,我不希望触发父级的事件。如果孩子有一个正常的事件侦听器,可以通过event.stopPropagation((来阻止它,但是当没有"事件"时我该怎么做呢?
<!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>
只需将单击侦听器添加到链接中,即可在其上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>
方法 1
如果子级有一个正常的事件侦听器,则可以通过 event.stopPropagation(( 来阻止它
。
是的。
但是当没有"事件"时我该怎么做呢?
有一个事件。你只是不听它。
您可以通过侦听子元素来解决问题:
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>
方法2
或者,您可以检查事件的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>
event
对象在onclick
处理程序中也可用:
<a id="child" href="https://i.kym-cdn.com/entries/icons/facebook/000/013/564/doge.jpg"
onclick="event.stopPropagation()">Text</a>
灵感来源于此。
⚠️ 与Internet Explorer不兼容,但是它可以在Edge上正常工作(在v89上测试(。
试试这个。
document.getElementById(id-here).addEventListener("click", function(e) {
e.stopImmediatePropagation();
console.log("clicked");
});
根据我的经验,打电话给event.stopImmediatePropagation();
会给你预期的结果。