首页 > 解决方案 > getElementById 变量范围

问题描述

在以下示例中,为什么不能从函数内部访问“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>

标签: javascriptscopegetelementbyid

解决方案


由于定时器下的函数在下一个事件周期执行,它不会知道状态。如果要传递“状态”,则应将其作为参数传递给 settimeout 函数,如下所示:-

 var status = document.getElementById("Label");
function Ticker(status) {
        setTimeout(Ticker, 100,status);      
        if (run) {
          status.value = "Connected";
        } else {
          status.value = "Disconnected";
        }
      }

推荐阅读