简体   繁体   中英

JQuery events not always firing

I'm working on a full AJAX app. When I load a new AJAX element, I use callbacks to set handlers on it. To be sure not to be trying to bind a non yet exisiting element, I put the listener on some parent. For example I do this :

$el.on( 'click',"#popin a.closePopin", function(e) { 
        e.preventDefault();
        closePopin(); 
});

This works... 80% percent of time.

My question is, what about the other 20% when nothing is fired?

Thanks.

EDIT : After reading the first answer and comment, I want to precise that the issue is happening randomly on the same elements without updating the code. And $el is a fixe container which never changes or disapear, also the ajax content is necessarly descendant of it.

To avoid this you should not attach the delegated event to $el thus making only descendant elements matching the selector fire the event but rather attach it to document .

$(document).on('click', "#popin a.closePopin", function(e) { 
    e.preventDefault();
    closePopin(); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM