简体   繁体   中英

Best Practice for Updating Listeners after Ajax Load

What's the best way of updating my Javascript event listeners after I load new content onto the page? I realized my click listener wasn't working if I added it before I loaded data into my feed. To fix this problem I put it in the .done callback of my ajax call.

$(".likebutton").click(function(){
    //function
});

If I load more data into the same feed the click listener gets added again to all the instances of .likebutton that were there before. This means sometimes my function gets called 2 or even 3 times depending on how many times I've loaded new data.

I know I can remove a listener on all objects and then add a new one each time, but I'm not sure if that's the best practice.

Suggestions?

Supposing that you always load the new content inside a specific element, like a div with id content , you could use the on method to delegate the click event to this element.

$('#content').on('click', '.likebutton', function() {
    // your code
});

Example: http://jsfiddle.net/nxpgp/ (note that every new .likebutton will respond to the click event)

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