使用 setInterval 移动轮播
我试图使用以下代码每秒移动轮播元素:
function moveCarousel(){
var x = $('.carousel_title.active');
var next = x.next();
x.removeClass('active');
next.addClass('active');
}
setInterval(moveCarousel(),1000);
但有两件事似乎出了问题:
- 第一个循环立即发生
- 没有进一步的循环发生
我哪里出错了?
I am trying to use the following code to move carousel elements through every second:
function moveCarousel(){
var x = $('.carousel_title.active');
var next = x.next();
x.removeClass('active');
next.addClass('active');
}
setInterval(moveCarousel(),1000);
but two things seem to go wrong:
- The first cycle happens instantly
- No further cycles occur
Where have I gone wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你应该删除最后一行的大括号
在这种情况下,你将一个函数(
moveCarousel
)传递给另一个函数(setInterval
),因此该函数不会被执行(这就是大括号的用途)但要像对象一样传递。您的原始代码将
undefined
(因为moveCarousel
不返回任何内容)传递给 setInterval 函数 - 并且 setInterval 将一个函数作为它的第一个参数 - 而不是undefined
您也可以这样做:
构造一个匿名函数来调用 moveCarousel。
you should remove the braces on your last line
In this case you are passing a function (
moveCarousel
) to a nother function (setInterval
) and thus the function is not to be executed (that's what the braces are for) but to be passed like an object.Your original code was passing
undefined
(becausemoveCarousel
does not return anything) to the setInterval function - and setInterval takes a function as it's first parameter - notundefined
You could also do this:
where you construct an anonymous function to call moveCarousel.
您正在调用应该传递函数本身的函数:
当前,您立即调用该函数,它的计算结果为:(
该函数不返回任何内容,因此它返回
未定义
),这不是您想要的。You're calling the function where you should pass the function itself:
Currently, you call the function immediately and it evaluates to:
(the function returns nothing so it returns
undefined
), which is not what you want.