jquery 添加类在 setinterval 中不断重置

jquery addclass keeps reseting inside setinterval

我有一个 HTML DIV,它由 ajax 函数使用 setinterval 更新。我想要做的是将 class 添加到 ajax 的结果中。但是当 setinterval 时,addedclass 被重置并显示初始 class。如何解决这个问题。

<html>
<body>
<div id="something"></div>

<script>
$(document).ready(function(){
var id;
setInterval(function(){
somepage();
  addactiveclass();
 }, 5000);

function somepage(){
$.ajax({
  url:"fetchcontents.php",
  method:"POST",
  success:function(data){
  $('#something').html(data);
  }
 })
}
function addactiveclass(){
$('#list-'+id).addClass("active");
}
// UPDATED
$(document).on('click', '.mycontents', function(){
id = $(this).data('id');
$('#list-'+id).addClass("active");
}

});
</script>
</body>
</html>

更新: fetchcontents.php

<?php
     $output .= '<div class="list-item mycontents" data-id="'.$row['id'].'" data-name="'.$row['username'].'" id="list-'.$row['id'].'">';
//.... some php function to generate some contents inside the above div.....
// Contents do not interfere with this question.
$output .= '</div>';

echo $output;
?>

发生的情况是活动类未添加到 div id="list-'.$row['id'].'"。如您所知,setinterval 在 5 秒后继续执行 ajax 函数,并且活动的 class 被重置并且不显示。

谁能指导我完成这个问题。

提前致谢。

我只是 运行 你在 jsfiddle 中的代码,但是用定义新 div 的字符串替换了 ajax 作为 #something 的内容,并且它有效。

但是它确实需要我将 js 放在 $(document).ready 块中

$(document).ready(function() {
    //your js in here
})

试试看。在呈现所有 HTML 之前,这不会定义 js。我的猜测是您引用了 #something 之前的内容。

编辑:=========================================== ==

自从我写完答案后,您已经对代码进行了相当大的更改,但是为了支持我声称对我认为是您的问题有解决方案的说法,我重新做了我的 jsfiddle 测试:https://jsfiddle.net/uf5h0sgw/

<html>
<body>
<div id="something">AAAA</div>

<script>
$(document).ready(function(){
  var id;
  var cnum = 1;
  setInterval(function(){
    somepage();
    addactiveclass();
   }, 1000);

  function somepage(){
  $('#something').html('<div class="abc">BBBB</div>');
  /*$.ajax({
    url:"fetchcontents.php",
    method:"POST",
    success:function(data){
    $('#something').html(data);
    }
   })*/
  }
  function addactiveclass(){
    /*$('#list-'+id).addClass("active"); */
    $('#something div').addClass("active" + cnum++)
  }

});
</script>
</body>
</html>

我无法重现您的 ajax 响应,所以我刚刚添加了一些代码以在每次间隔到期时将 DIV 插入#something(测试时减少到 1000 毫秒)。

然后函数 addactiveclass() 更改已添加的 Div 的 class。我在每个循环中更改计数器上的 class 名称,因此您可以看到 class 每次都会更新。

您显然必须调整我的代码来处理您的 AKAX 添加的任何内容,但该方法应该可以实现我认为您想要的。