jQuery stopPropagation冒泡 [英] jQuery stopPropagation bubble down

查看:92
本文介绍了jQuery stopPropagation冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有链接的div:

I have a div with a link inside of it:

<div id="myDiv">
    <a href="http://www.lol.com">Lol</a>
</div>

单击<div />应该转到某个位置,但是单击子级<a />应该转到www.lol.com.我从以前的问题

Clicking the <div /> should go somewhere, but clicking the child <a /> should go to www.lol.com. I've seen from previous questions and the jQuery website that .stopPropagation prevents bubbling upwards, but how do I prevent a bubble downwards (isn't that what's necessary here?).

推荐答案

事件只会冒出.因此,将在div的click事件处理程序之前触发a元素的click事件处理程序.如果您想要描述的行为,则需要向a元素添加click事件处理程序,以停止向div传播.

Events only bubble up. So the click event handler for the a element is fired before the click event handler for the div. If you want the behaviour you describe, the you need to add a click event handler to the a element which stops propagation to the div.

$("#myDiv a").click( function(event) {
    event.stopPropagation();
} );

并保留div上具有的所有事件处理程序.这应该允许事件执行其默认操作,并防止触发div上的处理程序.

and keep whatever event handler you have on the div. This should allow the event to perform it's default action, and prevent the handler on the div being fired.

如果只想防止点击链接,则可以更改div元素的事件处理程序

If you only want to prevent clicks on links then you can change your event handler for the div element

$("#myDiv").click( function( event ) {
    if( !$( event.target ).is( "a" ) )
    {
        // existing event handler
    }
} );

这篇关于jQuery stopPropagation冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆