Zeb*_*ian 11 javascript stoppropagation
当我点击我的 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>
Run Code Online (Sandbox Code Playgroud)
只需向链接添加一个点击监听器即可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');
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
如果子进程有一个正常的事件监听器,则可以通过 event.stopPropagation() 来阻止
是的。
但是当没有“事件”时我该怎么做呢?
有一个事件。你只是没有在听而已。
您可以通过监听子元素来解决问题:
document.getElementById("parent").addEventListener("click", function() {
alert("Oh no, you clicked me!");
});
document.querySelector("a").addEventListener("click", function(e) {
e.stopPropagation();
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
或者,您可以检查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!");
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15445 次 |
| 最近记录: |