[英]setTimeout() not working
我想每1秒計算一下下面的文本框的數量。 我像下面那樣嘗試過。但這不起作用...我不知道我在哪里弄錯了。 而且我想在文本框值達到10后停止該計數。請給我一個解決方案...謝謝
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var fun = function()
{
var count = $("#target :text").val();
$("#target :text").val(count++);
setTimeout(fun, 1000);
}
fun();
</script>
<div id="target">
<input type="text" value="0">
</div>
使用++count
而不是count++
,代碼的問題是您正在使用后增量。
$("#target :text").val(++count);
此外,我建議您使用可用於文檔的處理程序。
預增量示例
var count = 0; //Suppose
$("#target :text").val(++count);
相當於
var count = 0;
count = count + 1;
$("#target :text").val(count); //Will set value as 1
POST增量示例
var count = 0; //Suppose
$("#target :text").val(count++);
相當於
var count = 0;
$("#target :text").val(count); //Will set value as 0
count = count + 1;
問題是, val()
給您一個string 。
var fun = function() {
var el = $("#target :text");
var count = parseInt(el.val(), 10);
el.val(count+1);
setTimeout(fun, 1000);
}
fun();
您可以這樣操作,實際上是在計算秒數而不是計數器:
var t = new Date(), a = setInterval(function() {
$("#target>").filter(':input').val(function() {
if ((c = (Date.now() - t.getTime()) / 1000) >= 10)
clearInterval(a);
return Math.round(c);
});
}, 1000);
演示在這里 。
編輯:
只是因為我愛Coffeescript:
t = new Date()
a = setInterval ->
$('#target>').filter(':input').val ->
clearInterval a if (c = (Date.now() - t.getTime()) / 1000) >= 10
Math.round c
, 1000
大多數答案都是錯誤的,令人困惑的,並且沒有弄清這到底是什么錯誤。 您設置間隔循環的方式是完全正確的。
您錯過的是count++
將返回count
然后增加它。 因此,您始終將計數設置為0
。 您首先需要增加count
,然后進行設置。 您可以使用Satpal建議的++count
。
我認為為它創建一個臨時變量會更干凈,例如var updatedTime = count + 1;
然后將其設置為updatedTime
。 這樣一來,更容易被您的bug咬住,變得更加清晰和困難。 在功能上,這兩種方法是相同的。
保持簡單 :
function fun (){
$("#target :input").val(function(){return +this.value + 1;});
setTimeout(fun, 1000);
}
演示: http : //jsfiddle.net/39qVC/
var fun = function ()
{
var count = $("#target :text").val();
if(count >= 10) {
clearTimeout(loop);
}
else
{
$("#target :text").val(parseInt(count, 10) + 1);
}
}
var loop;
$(document).ready(function(){
var count = $("#target :text").val();
loop = setInterval(fun , 1000);
});
這些答案都沒有考慮到setTimeout或setInterval不是實時操作。 您的時間將會關閉。 不要使用計數器。
使用Date對象計算經過的時間,顯示經過的秒數,然后可以使用setInterval更新視圖。
請嘗試在下面編寫其工作代碼。
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function fun()
{
var count = $("#target :text").val();
count= parseInt(count) +1;// We have to parse value in to the int or other datatype.
$("#target :text").val(count);
}
setInterval('fun()', 100);
</script>
<div id="target">
<input type="text" value="0">
</div>
我們需要分析計數值,因為它是字符串格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.