jQuery $(element).each函数不适用于新添加的元素

Pri*_*ome 17 jquery jquery-selectors

我正在使用.each函数来迭代元素列表.我有匹配元素的初始列表和.each在这些方面很有效.但是我可以通过AJAX方法添加新的元素....但是这些新添加的元素不起作用吗?

我知道有关新添加的元素的实时事件和重新绑定事件,但是.each不是事件我找不到任何有关如何正确使用它来影响新添加的元素的帮助.

怎么解决这个?

//Uploadify callback where I add new items
onComplete: function(event, queueID, fileObj, response, data)
{
    $(".blank").remove();
    $("#lib-contentWrap").append(response); 
}
});

//And my each loop where I loop the elements. All elements are wrapped inside the #lib-contentWrap div. And the looping begins if I change the state of a checkbox (=checkbox check/uncheck)! $('#chk-selected').change(function(){ if( $(this).is(':checked') ) { $(".lib-item").each(function () { if ( $(this).hasClass('item-selected') ) $(this).slideDown('fast'); }); } else { $(".lib-item").each(function () { if ( $(this).hasClass('item-selected') ) $(this).slideUp('fast'); }); } });

谢谢,Primoz

Nic*_*ver 11

这是因为.each()当它运行时循环通过匹配的元素...当你调用它时,新的元素不在那里做事情.解决方案:再次调用它,但仅在添加新元素时调用它.您需要.each()在ajax结果上调用相同的结果,并使用结果的上下文来限制每个结果.

例如,如果您当前有此:

$(".myDiv").each(function() {
 //stuff here
});
Run Code Online (Sandbox Code Playgroud)

您需要在成功中调用相同的选择器和相同的代码(或完成,无论您使用什么)ajax函数如下:

success: function(resp) {
  $(".myDiv", resp).each(function() { //each, but only on the new guys
   //stuff here (same as before)
  });
  //Do more stuff with your response...
}
Run Code Online (Sandbox Code Playgroud)

这里的关键是, resp位,它告诉jQuery选择你以前的相同元素,但只在第二个参数的上下文中,在这种情况下:你的ajax响应包含需要爱的新元素.

根据新的问题代码进行更新

首先,您可以在此处缩短代码(可选不需要):

$('#chk-selected').change(function(){
    if($(this).is(':checked')) {
        $(".lib-item.item-selected").slideDown('fast');
    }
    else {
        $(".lib-item.item-selected").slideUp('fast');
    }
});
Run Code Online (Sandbox Code Playgroud)

在回调中,触发相同的处理程序再次运行(这不会更改选择,只是触发处理程序运行):

onComplete: function(event, queueID, fileObj, response, data)
{
    $(".blank").remove();
    $("#lib-contentWrap").append(response); 
    $('#chk-selected', response).trigger('change');
}
Run Code Online (Sandbox Code Playgroud)