简体   繁体   English

为什么它在document.onload中不起作用?

[英]Why it doesn't work in document.onload?

<script>
    window.onload= function(){
        var a = document.getElementById('a');
        var b = document.getElementById('ct');
        setInterval('b.innerHTML = a.duration',1000);
   };
</script>
//Second  script
<script>
    var a = document.getElementById('a');
    var b = document.getElementById('ct');
    window.onload= function(){
        setInterval('b.innerHTML = a.duration',1000);
    };
</script>

Why the first script is not working?. 为什么第一个脚本不起作用?

Chrome: 铬:

Uncaught ReferenceError: b is not defined 未捕获的ReferenceError:b未定义

You need to specify a function as argument to the setInterval , you have problem here: 你需要指定一个函数作为setInterval参数,你有问题:

setInterval('b.innerHTML = a.duration',1000);

Should be: 应该:

setInterval(function foo(){b.innerHTML = a.duration},1000);

My guess would be: because you use var on a and b in the first script. 我的猜测是:因为你在第一个脚本中使用了ab var This makes the variables local ones in window.onload (instead of global), and the code in setInterval cannot access them. 这使得变量本地变量在window.onload (而不是global)中,并且setInterval的代码无法访问它们。

Remove the var and it should work. 删除var ,它应该工作。

setInterval runs in the global scope. setInterval在全局范围内运行。 Any variables you refer to in setInterval that are not accessible from the global scope -- like the local a and b in the first example -- will be undefined at execution time. 您在setInterval中引用的无法从全局范围访问的任何变量(如第一个示例中的本地ab将在执行时未定义。

in the first script "a" and "b" are a variables defined in the scope of the event. 在第一个脚本中,“a”和“b”是在事件范围内定义的变量。 The "setInterval" looks for the "innerHTML" property in the document (global) scope. “setInterval”在文档(全局)范围中查找“innerHTML”属性。 In the second sample "a" and "b" are outside the event definition, ie defined directly in the document scope so they are reconized by the "setInterval" function. 在第二个样本中,“a”和“b”在事件定义之外,即直接在文档范围中定义,因此它们通过“setInterval”函数进行重新计算。

You can not reference the documents elements in .onload because the document hasn't been loaded there yet. 您无法在.onload中引用文档元素,因为尚未加载文档。 Move the code to the end of the document just before </body> . 将代码移到</body>之前的文档末尾。

It also avoids problems with multiple event handlers in .onload as you are actually overwriting any pre-existing eventhandlers. 它还避免了.onload中多个事件处理程序的问题,因为您实际上覆盖了任何预先存在的事件处理程序。 Use addEventListener for attaching eventhandlers. 使用addEventListener附加事件处理程序。

like this: 像这样:

<body>

// markup

<script>
var a = document.getElementById('a');
var b = document.getElementById('ct');


setInterval('b.innerHTML = a.duration',1000);

</script>

</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM