简体   繁体   English

带有AJAX轮询的jQuery .live()和.each()

[英]jQuery .live() and .each() with AJAX polling

I have a simple function that goes through the page and adds a CSS class to each element that matches, using .each() . 我有一个遍历页面的简单函数,并使用.each()将CSS类添加到匹配的每个元素中。 I'm also constantly updating the page with AJAX, and after the first AJAX update that changes things, the function no longer applies. 我还不断使用AJAX更新页面,并且在第一次更改的AJAX更新之后,该功能不再适用。

Code: 码:

$("div.col-conversation span.label-sticky").each(function () {
    $(this).closest('li').addClass('stickyhighlight');
});

I understand why it doesn't work after the first AJAX event and went to try to use .live() or .delegate() but it doesn't appear that you can bind things that aren't events (ie you can only bind to click, hover etc.) using this method, so .each() isn't going to work. 我了解为什么在第一个AJAX事件之后它不起作用,并尝试使用.live().delegate()但似乎您可以绑定非事件的东西(即,您只能绑定单击,悬停等),因此.each()无法正常工作。

Is there a simple way to execute this function without including it in the AJAX success callback and without using a plugin like livequery, which is probably overkill? 有没有一种简单的方法可以执行此功能,而不必将其包含在AJAX成功回调中,也可以不使用诸如livequery之类的插件,这可能是过大了?

What's probably better than attaching an event handler for each matching item is to attach an event with jQuery.on() with a selector parameter. 与为每个匹配项附加事件处理程序相比,最好是使用带有选择器参数的jQuery.on()附加事件。 It allows you to do something like: 它允许您执行以下操作:

$('#container').on('click', '.yourClass', function(event){ doStuff(); });

with

<div id="container">
    <span class="yourClass">...</span>
    <div class="yourClass">...</div>
    <anything class="yourClass">...</anything>
</div>

This means that only one event listener needs to be active instead of one event per item with the class. 这意味着该类仅需要一个事件侦听器处于活动状态,而不是每个项目一个事件。 It also means that if you add items to the container, you won't need to update the listener. 这也意味着,如果将项目添加到容器中,则不需要更新侦听器。 It's better performance and easier to deal with. 它具有更好的性能并且更易于处理。

Check jQuery.com for more about .on(). 检查jQuery.com以获取更多有关.on()的信息。

I think this will work for you: 我认为这将为您工作:

$('body').on('mychange','div.col-conversation span.label-sticky',function () {
   $(this).closest('li').addClass('stickyhighlight');
});

Add this to your ajax success function: 将此添加到您的ajax成功函数中:

$('body').trigger('mychange');

OR if you really don't want to (or can't) modify the ajax success function: 或者,如果您确实不想(或不能)修改ajax成功函数:

setInterval(function() {
   $('div.col-conversation span.label-sticky').each(function () {
       $(this).closest('li').addClass('stickyhighlight');
   });
},100);

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

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