开发者

How to stop events bubbling in jQuery? [duplicate]

This question already has answers here: How do I prevent a parent's onclick event from firing when a child anchor is clicked? (25 answers) Closed 5 years ago.

How do I stop custom event bubbling in jQuery?

For example I have this code:

$('.myclass').bind('amodaldestroy', function(){
    ....does something.....
})

How do I only allow this to be triggered once on the first element it finds when bubbling? Can I just a开发者_JAVA百科dd return false?

$('.myclass').bind('amodaldestroy', function(){
     ....does something.....
    return false;
})


According to jQuery's documentation:

$('myclass').bind('amodaldestroy'), function(event) {
    ....does something....
    event.stopPropagation();
});


Use event.stopPropagation();

$('.myclass').bind('amodaldestroy', function(e){
    e.stopPropagation();
});

You can also use return false but there is a subtle difference between the two in that returning false also calls event.preventDefault();


For support in IE < 9:

$(".element").click(function(e)
{
    var event = e || window.event;
    event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);
});


This might not be that great but

return false;

return false will do both stopPropagation and event.preventDefault...

if you want only one you can choose based on your choice

please read this , this is from SO only

return false is effectively both preventDefault and stopPropogation.

preventDefault will prevent the default event from occuring, stopPropogation will prevent the event from bubbling up and return false will do both.


http://api.jquery.com/event.stopPropagation/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜