javascript - 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>
解决方案
由于定时器下的函数在下一个事件周期执行,它不会知道状态。如果要传递“状态”,则应将其作为参数传递给 settimeout 函数,如下所示:-
var status = document.getElementById("Label");
function Ticker(status) {
setTimeout(Ticker, 100,status);
if (run) {
status.value = "Connected";
} else {
status.value = "Disconnected";
}
}
推荐阅读
- docker - 如何让容器关闭 Kubernetes 中的主机?
- php - laravel 5.6 与 guzzlehttp 6 试图获取非对象标题的属性
- javascript - ember 中的 helper 'andThen' 与传统的 'then' 有何不同
- android - 第一次更新后未触发 Firebase 数据库 onChildChanged()
- django - Django 与 BeautifulSoup 的 lxml 解析器的兼容性
- javascript - 如何使用codemirror显示像mozilla开发网络一样的代码输出?
- css - CSS @keyframes 动画在悬停时不断闪烁
- encryption - 如何使用 Virgil 安全加密和解密消息?
- google-app-engine - 谷歌应用引擎项目多区域部署
- angular - 我们如何在 Angular 4 应用程序中为特定的 html 页面导入条件 css 文件?