简体   繁体   中英

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

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, ie 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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