JQuery - 使用计时器循环一个类
我有一个下面的结构列表,
<div id="slider">
<ul>
<li class='active'> a </li>
<li> b </li>
<li> c </li>
<li> d </li>
<li> e </li>
</ul>
</div>
我需要以循环方式更改 li 的“active”类 这是我正在使用的脚本。问题是它要么将类 active 添加到所有 li 中,要么从所有 li 中删除类 active
toggleSlide = function(){
$("#slider ul li").each(function(index) {
if($(this).hasClass('active')){
$("#slider ul li").removeClass('active');
$(this).next().addClass('active'));
//lis = $("#slider ul li")
//$(lis[(index+1)%lis.length]).addClass('active');
}
});
}
setInterval(toggleSlide, 5000);
I've a list wit below structure
<div id="slider">
<ul>
<li class='active'> a </li>
<li> b </li>
<li> c </li>
<li> d </li>
<li> e </li>
</ul>
</div>
I need to change the class 'active' of li's in a cycling manner
Here is the script I'm working with. issue is it either adds the class active to all li's or removes the class active from all li's
toggleSlide = function(){
$("#slider ul li").each(function(index) {
if($(this).hasClass('active')){
$("#slider ul li").removeClass('active');
$(this).next().addClass('active'));
//lis = $("#slider ul li")
//$(lis[(index+1)%lis.length]).addClass('active');
}
});
}
setInterval(toggleSlide, 5000);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
.add()
和.last()
因为来自.add()
按文档顺序翻转,如下所示:您可以在此处进行测试(演示持续时间为 1000 毫秒)
这是如何工作的,它需要下一个
;
如果有一个,则使用.last()
(因为它们是按文档顺序排列的)我们将得到.next()
if 存在,否则该集合仅包含一个元素,即:first
You can greatly simplify this with
.add()
and.last()
since elements from.add()
are turned in document order, it would look like this:You can test it here (1000ms duration for the demo)
How this works is it takes the next
<li>
if there is one, then adds the first one as well, by using.last()
(since they're in document order) we'll get the.next()
one if it's there, otherwise the set only contains one element, the:first
<li>
, and we're back to the beginning.这应该会更好一些:
您不需要
.each()
循环,这就是导致问题的原因。您只需要处理当前活动的元素。实例:
This should work a bit better:
You don't need the
.each()
loop and that's what was causing your issues. You only need to work on the current active element.Live example:
我会选择更简单的
http://jsfiddle.net/HyRYC/1/
基本上,找到活动项目并将其保存到本地变量中。然后找到它后面的项目并保存它。现在,如果最后一个处于活动状态,则
next()
将返回一个没有匹配项的 jQuery 对象,这意味着它的长度为零。在这种情况下,找到第一个项目作为我们的下一个
。不,我们只需从当前活动项目中删除
active
类,并将其添加到下一个活动项目中。I'd go for something far simpler
http://jsfiddle.net/HyRYC/1/
Basically, find the active item and save it to a local var. Then find the item after it and save that too. Now if the last one is active, then
next()
will return a jQuery object with no matches, meaning it has a length of zero. In that case, find the first item to be ournext
.No we simply remove the
active
class from the current active item, and add it to our next one.