setInterval问题(js)
我已经尝试修复这个脚本一个多小时了,但仍然无法让它工作。它是一个在 setInterval 中执行 animate 和 html jquery 事件的循环。
这是小提琴: http://jsfiddle.net/GNrL3/
这是代码(与小提琴相同,但有些人更喜欢放在这里):
$(document).ready(function() {
var i = 1;
var startinterval = 0;
$('#clickhere').click(function() {
startinterval = setInterval("curvalues()", 1000);
});
function curvalues() {
if ($i == 20) {
clearInterval(startinterval);
}
else {
$("#square").animate({
"left": "+=30px"
}, "slow");
$("#text").html("Barracks");
$i++;
}
}
});
<div id="square" style="position:absolute;height:30px;width:30px;background-color:#F07014;"></div>
<br /><br /><br /><br /><br />
<div id="text" style="height:30px;width:100px;border:1px solid #000">Text box</div>
<br /><br />
<input type="button" value="Start" id="clickhere"/>
我相信问题涉及函数的 setInterval,但语法对我来说似乎很好......
I have been trying to fix this script for more than an hour and still can't get it to work. It is a loop performing animate and html jquery events in a setInterval.
Here is the fiddle: http://jsfiddle.net/GNrL3/
Here is the code (same as fiddle but some prefer to have it here):
$(document).ready(function() {
var i = 1;
var startinterval = 0;
$('#clickhere').click(function() {
startinterval = setInterval("curvalues()", 1000);
});
function curvalues() {
if ($i == 20) {
clearInterval(startinterval);
}
else {
$("#square").animate({
"left": "+=30px"
}, "slow");
$("#text").html("Barracks");
$i++;
}
}
});
<div id="square" style="position:absolute;height:30px;width:30px;background-color:#F07014;"></div>
<br /><br /><br /><br /><br />
<div id="text" style="height:30px;width:100px;border:1px solid #000">Text box</div>
<br /><br />
<input type="button" value="Start" id="clickhere"/>
My belief is that the issue concerns the setInterval of the function, but still, the syntax seems good to me...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有一个函数范围的问题。相反,
请执行以下操作:
编辑 您还有一个错误。您的计数器变量名称错误。它应该这样声明:(
或者用
i
而不是$i
引用所有变量)我更新了你的小提琴:http://jsfiddle.net/GNrL3/1/ 现在可以使用了。
希望这有帮助。干杯
You have a function-scope problem. Instead of this:
do this:
EDIT You have one more mistake. Your counter variable has a wrong name. It should be declared like this:
(or reference all your vars with
i
instead of$i
)I updated your fiddle: http://jsfiddle.net/GNrL3/1/ and it works now.
Hope this helps. Cheers
将此行更改
为:
或此:
并去掉
i
前面的$
。没必要这样。Change this line:
To this:
Or this:
And get rid of the
$
in front ofi
. There's no need for that.