[英]How do I prevent event propagation on link click?
當我點擊我的 a-tag 時,我不希望觸發父級的事件。 如果孩子有一個正常的事件監聽器,它可以被 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() { 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>
只需向鏈接添加一個單擊偵聽器,在該鏈接上執行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>
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();
根據我的經驗,會給你預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.