开发者

jQuery live method: can't stop event from bubbling the DOM

开发者 https://www.devze.com 2023-04-06 04:36 出处:网络
I\'m not sur开发者_如何学Pythone, but it seems like a bug. Here are samples: http://jsfiddle.net/QNrZu/

I'm not sur开发者_如何学Pythone, but it seems like a bug.

Here are samples:

http://jsfiddle.net/QNrZu/

Maybe i'm doing something wrong? Any solution for this?

Thanks ;)


Have you read the documentation?

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events.

.live() [docs] binds the event handlers to the document root. You can even see this in the order of the logs you get:

this should't be triggered
clicked

The event handler at the div is executed before the live handler for the a element.

If you have to use .live(), then the only way to solve this would be to also bind the event the event handler to the div with .live():

$('div').live('click', function(){
    console.log("this should't be triggered");
});

DEMO

If you don't have to use .live(), then just bind the handler to the a element in the normal way, using .click() [docs] or .bind() [docs].


use bind instead of live, live has to cater for the dynamically added elements so event bubbling cannot be stopped

   $('div').click(function(){
        alert('will not be triggered');
    });

    $('a').bind('click',function(e){
        console.log('clicked');   
        e.stopPropagation();
        alert("first");
        alert("second");    
    });

here is the fiddle http://jsfiddle.net/QNrZu/3/

0

精彩评论

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