Prevent click event from affecting parent jquery

2019-02-24 10:14发布

问题:

I was to stop the event propagation from the child to the parent, i have a bunch of li tags containing a.

$('li a[rel=close]').live('click', function(e){
    e.stopPropagation();
    e.preventDefault();
})

But it doesn;t stop the event.Any suggestions ?

回答1:

stopPropagation has problems with live, from the jQuery stopPropagation docs -

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

As Rob W has said your code would work fine with bind, here's a demo - http://jsfiddle.net/TmKyT/



回答2:

Use .bind instead of .live. The live event is triggered at the end of the propagation tree. live is only more useful than bind when you want to also bind the event listener for elements which are created later.



回答3:

Maybe try using delegate?

$('ul.parent').delegate('li a[rel=close]', 'click', function( event ) {

}