链接中的链接onClick事件 - 避免两个点击事件触发 [英] Link within a link onClick event - Avoid both click events triggering
问题描述
我在链接中有一个链接,都带有一个onClick事件。
外部链接按需要工作。但是,内部链接触发onClick事件。我希望它能够在单击内部链接时不触发外部事件。
< div onClick =console .LOG(1)>
< a href =#onClick =console.log(2)>内部< / a>
< / div>
JavaScript事件会通过树来传播。
因此,当你点击内部锚点时,它也会发出任何更高级元素的点击事件,所以 div
元素。
为了阻止这种情况发生,内部点击处理程序必须阻止事件通过 e.stopPropagation();
传播。 b
然而,当您在JavaScript中没有使用 .addEventListener()
注册处理程序时,这会变得有点麻烦。
如果你用这种方式添加事件,你可以这样做(首先给你的锚定一个id,比如说 inner
),这很好很容易:
document.getElementById('inner')。addEventListener('click',function(e){
e.stopPropagation ();
console.log(2);
});
但是,如果您希望使用该属性,则可以将事件传递到您的点击处理程序中,如下所示:
< a href =#onClick =innerHandler(event)>内部< / a>
// JS
函数innerHandler(e){
e.stopPropagation();
console.log(2);
}
一般来说(这是我的观点),我会避免后者。像这样登记的活动很难删除和修改。您不能轻易地将多个处理程序注册到相同事件的相同元素。
I have a link within a link, both with an onClick event.
The outer link works as desired. However, the inner link triggers both onClick events. I would like it so that the outer event is not triggered when the inner link is clicked.
<div onClick="console.log(1)">
<a href="#" onClick="console.log(2)">Inner</a>
</div>
Javascript events will propagate up through the tree.
So when you click on the inner anchor it will also emit any click events for elements higher up, so the div
element.
To stop this the inner click handler has to prevent the event from propagating with e.stopPropagation();
.
However this gets a little messy when you don't register handlers with .addEventListener()
in JavaScript.
If you add events this way you can do it like this (first give your anchor an id, say inner
) which is nice and easy:
document.getElementById('inner').addEventListener('click', function (e) {
e.stopPropagation();
console.log(2);
});
You can however pass the event into your click handler if you do wish to use the attribute, so:
<a href="#" onClick="innerHandler(event)">Inner</a>
//JS
function innerHandler(e) {
e.stopPropagation();
console.log(2);
}
Generally speaking (this is my opinion) i would avoid the latter. Events registered like this are difficult to remove and modify. You can't also easily register multiple handlers to the same element for the same event.
这篇关于链接中的链接onClick事件 - 避免两个点击事件触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!