开发者

Why it doesn't work in document.onload?

开发者 https://www.devze.com 2023-01-11 12:10 出处:网络
<script> window.onload= function(){ 开发者_Go百科var a = document.getElementById(\'a\'); var b = document.getElementById(\'ct\');
<script>
    window.onload= function(){
开发者_Go百科        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


You need to specify a function as argument to the setInterval, you have problem here:

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. This makes the variables local ones in window.onload (instead of global), and the code in setInterval cannot access them.

Remove the var and it should work.


setInterval runs in the global scope. 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.


in the first script "a" and "b" are a variables defined in the scope of the event. The "setInterval" looks for the "innerHTML" property in the document (global) scope. In the second sample "a" and "b" are outside the event definition, i.e. defined directly in the document scope so they are reconized by the "setInterval" function.


You can not reference the documents elements in .onload because the document hasn't been loaded there yet. Move the code to the end of the document just before </body>.

It also avoids problems with multiple event handlers in .onload as you are actually overwriting any pre-existing eventhandlers. Use addEventListener for attaching eventhandlers.

like this:

<body>

// markup

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


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

</script>

</body>
0

精彩评论

暂无评论...
验证码 换一张
取 消