setTimeout()不起作用

kal*_*yan 1 javascript

我想每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>
Run Code Online (Sandbox Code Playgroud)

Sat*_*pal 5

使用++count代替count++,代码的问题是您正在使用后增量.

$("#target :text").val(++count);
Run Code Online (Sandbox Code Playgroud)

DEMO

另外,我建议你使用文档就绪处理程序.

编辑

预增量示例

var count  = 0; //Suppose
$("#target :text").val(++count); 
Run Code Online (Sandbox Code Playgroud)

相当于

var count  = 0; 
count = count + 1;
$("#target :text").val(count); //Will set value as 1
Run Code Online (Sandbox Code Playgroud)

POST增量的示例

var count  = 0; //Suppose
$("#target :text").val(count++); 
Run Code Online (Sandbox Code Playgroud)

相当于

var count  = 0; 
$("#target :text").val(count); //Will set value as 0
count = count + 1;
Run Code Online (Sandbox Code Playgroud)