在 JavaScript 中自动递增计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15432724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto incrementing a counter in JavaScript
提问by Satinder Singh
I want to animate a counter from 0 to a given value automatically on page load. Recently I found one but it works with button click.
我想在页面加载时自动将计数器从 0 动画到给定值。最近我找到了一个,但它适用于按钮点击。
var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;
function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}
$('#runner').click(function(){
run();
});
SEE >> JS fiddle DEMO
看>> JS小提琴DEMO
Also I want to add a reset button in it which will run it again from 0 on every click.
此外,我想在其中添加一个重置按钮,每次单击时都会从 0 再次运行它。
回答by Zaheer Ahmed
Html:
网址:
<input type="hidden" value="10000" id="amount"/>
<input type="text" value="0" id="count"/>
<input type="button" value="Start" id="starter"/>
<input type="button" value="Stop" id="stopper"/>
<input type="button" value="reset" id="resetter"/>
Script:
脚本:
<script type="text/javascript">
var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;
function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}
run();
$('#stopper').click(function(){
clearInterval(tim);
});
$('#resetter').click(function(){
clearInterval(tim);
i=0;
$('#count').val(i);
run();
});
$('#starter').click(function(){
clearInterval(tim);
run();
});
</script>
回答by Darren
Use document ready:
使用文件准备好:
$(document).ready(function() {
run();
});
You can reset the counter by assigning count
to 0.
您可以通过分配count
为 0来重置计数器。
<input id="resetCount" type="button" />
function reset() {
$('#count').val(0);
}
$("#resetCount").click(function() {
reset();
});
回答by PSR
you can call a function in onload you can do there
你可以在onload中调用一个函数你可以在那里做
like
喜欢
<script>
run();
</script>
The run() function will call whenever the page is loading.
run() 函数将在页面加载时调用。
回答by benzonico
Just call your run method in document ready :
只需在文档就绪中调用您的 run 方法:
$(document).ready(function() {
run();
});