jquery addclass 在 setinterval 内不断重置

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


<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;

?>

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


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


慕仙森
浏览 102回答 1
1回答

GCT1015

我刚刚在 jsfiddle 中运行了你的代码,但用一个字符串替换了 ajax,将新的 div 定义为 #something 的内容,并且它有效。然而它确实需要我将 js 放入 $(document).ready 块中$(document).ready(function() {&nbsp; &nbsp; //your js in here})尝试一下。其作用是在渲染所有 HTML 之前不定义 js。我的猜测是您在 #something 存在之前引用了它。编辑:===============================================自从我写完答案以来,您已经对代码进行了很大的更改,但是为了支持我的主张,以解决我认为是您的问题,我重新完成了我的 jsfiddle 测试:https:&nbsp;//jsfiddle.net/uf5h0sgw/<html><body><div id="something">AAAA</div><script>$(document).ready(function(){&nbsp; var id;&nbsp; var cnum = 1;&nbsp; setInterval(function(){&nbsp; &nbsp; somepage();&nbsp; &nbsp; addactiveclass();&nbsp; &nbsp;}, 1000);&nbsp; function somepage(){&nbsp; $('#something').html('<div class="abc">BBBB</div>');&nbsp; /*$.ajax({&nbsp; &nbsp; url:"fetchcontents.php",&nbsp; &nbsp; method:"POST",&nbsp; &nbsp; success:function(data){&nbsp; &nbsp; $('#something').html(data);&nbsp; &nbsp; }&nbsp; &nbsp;})*/&nbsp; }&nbsp; function addactiveclass(){&nbsp; &nbsp; /*$('#list-'+id).addClass("active"); */&nbsp; &nbsp; $('#something div').addClass("active" + cnum++)&nbsp; }});</script></body></html>我无法重现您的 ajax 响应,因此我刚刚添加了一些代码,以便在每次间隔到期时将 DIV 插入到 #something 中(测试时减少到 1000 毫秒)。然后函数addactiveclass()改变已经添加的Div的类。我在每个循环的计数器上更改类名称,以便您可以看到该类每次都会更新。显然,您必须调整我的代码来处理 AKAX 添加的任何内容,但该方法应该实现我认为您想要的效果。
打开App,查看更多内容
随时随地看视频慕课网APP