我有以下标记
<div class="main">
<ul class="ajax-terms">
<li id="app-105">Find Friends</li>
<li id="app-107">Buy Tickets,Pay Cover Charges</li>
<li id="app-114">Pre-purchase bottle service</li>
<li id="app-117">Book VIP Services</li>
<li id="app-120">Buy Merchandise</li>
<li id="app-122">Toast Friends worldwide</li>
<li id="app-125">Notify Services & split the tab</li>
</ul>
</div>
我想添加一个类myclass
从第一个li
一个接一个的元素。假设它被添加到第一个 li
元素,然后 5 秒后它将被添加到第二个 li
并将其从第一个 li
中删除,然后添加到第三个li
并将其从第二个 li
中删除然后依此类推。当到达最后一个li
时,它应该再次从第一个 li
重新启动这样循环就会继续下去。
目前我的代码如下:
$('.main li').each(function(i, el) {
setTimeout(function() {
$(el).addClass('myclass');
}, i * 3000);
setTimeout(function() {
$(el).removeClass('myclass');
}, i * 3500);
});
我面临的问题:
1) 到达最后一个时不重复 li
.
2) 从第二个开始li
,不是第一个(可能是一些延迟问题)
任何帮助将不胜感激。
最佳答案
使用setInterval
而不是setTimeout
。
var count=0; // flag
var len = $('.main li').length; // Get the total length of the li to iterate the loop
setInterval(function(){ // Execute a function in every 1 sec
if(count === len){
count = 0; // Reset the flag to restart the loop
}
$('.main').find(".myclass").removeClass("myclass"); // Before adding the class, first find it and remove the class
$('.main li').eq(count).addClass("myclass"); // eq(count) gives the specific li children where we want the class to be added
count++;
}, 1000);
关于javascript - 如何在不刷新页面的情况下重复each(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885369/