使用“jquery”的函数的奇怪行为
功能比较简单。当你点击按钮时,一个物体就会掉下来。如果再次按下按钮,物体会回到其随机位置并再次以相同的速度落下。 但每次我单击按钮时,它(边缘顶部)都会变得更快。我不明白为什么?
HTML
<button id="fall" onclick="show_up()"> random-fall </button>
<div id="box" style="width:20px;height:20px;background:blue;"> </div>
脚本
var top;
function show_up() {
top = 0;
$("#box").css("margin-top", top);
var rand = Math.random() * 500;
rand = parseInt(rand);
$("#box").css("margin-left", rand);
fall_out();
}
function fall_out() {
top++;
if (top < 500) {
$("#box").css("margin-top", top);
window.setTimeout('fall_out()', 10);
}
else {
top = 0;
fall_out();
}
}
谁能告诉我解决这个问题的最佳方法吗?
The function is relatively simple. When you click the button, an object will fall down. if you press the button again, the object go back to its random position and fall down again at the same speed.
but everytime I click the button, it (margin-top) gets much faster. I don't understand why?
HTML
<button id="fall" onclick="show_up()"> random-fall </button>
<div id="box" style="width:20px;height:20px;background:blue;"> </div>
Script
var top;
function show_up() {
top = 0;
$("#box").css("margin-top", top);
var rand = Math.random() * 500;
rand = parseInt(rand);
$("#box").css("margin-left", rand);
fall_out();
}
function fall_out() {
top++;
if (top < 500) {
$("#box").css("margin-top", top);
window.setTimeout('fall_out()', 10);
}
else {
top = 0;
fall_out();
}
}
Could anyone tell me the best way to solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码的问题是
fall_out()
永远不会停止。它会继续调用自己。阅读您的评论@Joop Eggen的回答后,这似乎是理想的行为。当您第二次调用
show_up()
时,fall_out()
将再次调用,从而导致第二个无限循环强>。这就是为什么你的对象会更快下落,fall_out()
会比第一次更频繁地被调用(因为有 2 个递归循环)。您不得在
show_up()
中多次调用fall_out()
。您可以设置一个像这样的变量 (started< /代码>):
The problem with your code is that
fall_out()
will never stop. It'll go on calling itself. After reading your comment @ Joop Eggen's answer it seems to be desired behavior.When you call
show_up()
a second time,fall_out()
will be called again which results in a second infinite loop. That's the reason why your object is going to fall faster,fall_out()
will be called more often than the first time (because of the 2 recursive loops).You must not call
fall_out()
inshow_up()
more than once. You can e.g. set a variable like this (started
):应该删除 else 分支中最后一次对 fall_out() 的递归调用,并将 margin-top 设置为 0。否则递归将是无限的。
The last recursive call to fall_out() in the else branch should be removed, and margin-top set to 0. Otherwise recursion is endless.
您正在使用随机函数。这个脚本只是将盒子移动到 x 轴的随机位置
you are using random function. this script is just moving the box in random position in x-axis