我有以下DIV结构:

<div id='mainDiv'>
  <div id='childDiv1' class='childElement'>Content1<div>
  <div id='childDiv2' class='childElement'>Content2<div>
</div>



  在我的Jquery操作之一中,我正在删除的所有内容
  mainDiv


 strHtmlNewChildHtml = '<div id='childDiv1' class='childElement'>New Content1<div><div id='childDiv2' class='childElement'>New Content2</div>';

 $("#mainDiv").html('');
 $("#mainDiv").html(strHtmlNewChildHtml);



  并使用循环的类名添加新HTML。


$('.childElement').each( function() {
//It is looping 4 times while new HTML having only 2 divs
 });


我的问题:当循环运行4次时,我已删除了旧的2个子元素,并添加了2个新的子元素,因此?

最佳答案

jQuery调用$('.childElement')将在调用时查找元素。因此,如果此时您的代码中有4个.childElement,那么它将循环4次。

关于javascript - 循环每个Jquery中的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44690983/

10-13 05:32