简体   繁体   English

在Ajax加载之后更新侦听器的最佳实践

[英]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? 将新内容加载到页面后,更新Javascript事件侦听器的最佳方法是什么? I realized my click listener wasn't working if I added it before I loaded data into my feed. 我意识到,如果我在将数据加载到Feed中之前添加了点击侦听器,那么它就无法正常工作。 To fix this problem I put it in the .done callback of my ajax call. 为了解决这个问题,我将其放在ajax调用的.done回调中。

$(".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. 如果我将更多数据加载到同一Feed中,则点击侦听器会再次添加到之前存在的.likebutton的所有实例中。 This means sometimes my function gets called 2 or even 3 times depending on how many times I've loaded new data. 这意味着有时我的函数会被调用2次甚至3次,具体取决于我加载新数据的次数。

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. 假设您始终将新内容加载到特定元素中,例如id为content的div,则可以使用on方法将click事件委托给该元素。

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

Example: http://jsfiddle.net/nxpgp/ (note that every new .likebutton will respond to the click event) 示例: http : //jsfiddle.net/nxpgp/ (请注意,每个新的.likebutton都会响应click事件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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