且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在单击子锚点时阻止父级的onclick事件触发?

更新时间:2021-11-26 04:26:06

事件泡到DOM中的最高点已附加点击事件。所以在你的例子中,即使div中没有​​任何其他明确可点击的元素,div的每个子元素都会将它们的click事件向上冒泡到DOM,直到DIV的click事件处理程序捕获它为止。

Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.

这有两个解决方案,即检查实际发起事件的人。 jQuery传递一个eventargs对象以及事件:

There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:

$("#clickable").click(function(e) {
    var senderElement = e.target;
    // Check if sender is the <div> element e.g.
    // if($(e.target).is("div")) {
    window.location = url;
    return true;
});

您还可以在链接上附加一个点击事件处理程序,告诉他们在自己的处理程序执行后停止事件冒泡

You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:

$("#clickable a").click(function(e) {
   // Do something
   e.stopPropagation();
});