在下面的示例中,为什么不能从函数内部访问“status.value”?如果我将函数中的'status.value‘替换为document.getElementById("Label").value,一切都会正常工作。谢谢。
<html>
<body onload="Ticker()">
<label>Connection Status:</label>
<input type="text" readonly="true" value="Idle" id="Label">
<input type="button" value="Start/Stop" onclick="run=!run">
<br>
<script>
var status = document.getElementById("Label");
var run;
function Ticker() {
setTimeout( Ticker, 100 );
if(run){
status.value = "Connected";
}else{
status.value = "Disconnected";
}
}
</script>
</body>
</html>发布于 2018-06-28 18:53:07
<html>
<body onload="Ticker()">
<label>Connection Status:</label>
<input type="text" readonly="true" value="Idle" id="Label">
<input type="button" value="Start/Stop" onclick="run=!run">
<br>
<script>
var run;
function Ticker() {
setTimeout(Ticker, 100);
var status = document.getElementById("Label");
if (run) {
status.value = "Connected";
} else {
status.value = "Disconnected";
}
}
</script>
</body>
</html>
发布于 2018-06-28 19:23:12
由于计时器下的函数在下一个事件周期中执行,因此它不会知道状态。如果你想传递'status‘,你应该把它作为参数传递给settimeout函数,如下所示:
var status = document.getElementById("Label");
function Ticker(status) {
setTimeout(Ticker, 100,status);
if (run) {
status.value = "Connected";
} else {
status.value = "Disconnected";
}
}https://stackoverflow.com/questions/51079693
复制相似问题