setInterval 的问题
我只是想用 jQuery 实现 setInterval 的最基本示例,但遇到了问题。这是怎么回事?
它说函数旋转未定义。
$(document).ready(function() {
var speed = 5000;
var run = setInterval("rotate()", speed);
function rotate() {
alert ('rotate');
}
});
I am just trying to implement the most basic example of setInterval with jQuery and am having problems. What's wrong here?
It says function rotate is not defined.
$(document).ready(function() {
var speed = 5000;
var run = setInterval("rotate()", speed);
function rotate() {
alert ('rotate');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这样做:
您也可以简单地这样做:
如果您希望稍后能够清除间隔,则应该在就绪事件处理程序之外声明
run
,否则它将超出范围。Do this instead:
You could also simply do this:
You should declare
run
outside the ready event handler if you wish to be able to clear the interval later though, since it will go out of scope otherwise.您正在将
setInterval
字符串传递给 eval。这是:该函数的范围仅限于其内部定义的函数。
直接传递函数即可
You are passing
setInterval
a string to eval. This is:The function is limited in scope to the function it is defined inside.
Pass the function directly instead
在 setInterval 调用中省略旋转的括号和引号。您给它的是函数本身,而不是名称。他们进入的顺序应该不重要。
omit the parenthesis and quotes around rotate in your setInterval call. You are giving it the function itself, not the name. It shouldn't matter the order that they go in.
这实际上是在(我认为是)它自己的上下文中进行轮换评估。改成这样
应该就可以了。
That's effectively eval-ing rotate in (what I believe is) its own context. Change it to
and it should be fine.
或者甚至将旋转函数放在就绪函数之外。
or even put the rotate function outside the ready function.
这有效
this works
您需要在全局范围内定义
rotate
。You need to define
rotate
in the global scope.