在以下示例中,为什么不能从函数内部访问“ status.value”? 如果我在函数内用document.getElementById(“ Label”)。value替换“ status.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>
答案 0 :(得分:0)
<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>
答案 1 :(得分:0)
由于计时器下的功能在下一个事件周期中执行,因此不会知道状态。如果要传递“状态”,则应将其作为参数传递给settimeout函数,如下所示:-
var status = document.getElementById("Label");
function Ticker(status) {
setTimeout(Ticker, 100,status);
if (run) {
status.value = "Connected";
} else {
status.value = "Disconnected";
}
}