开发者

Why doesn't this piece of JavaScript code work when placed inside <head> but works when placed at the bottom of <body>

I was trying to write this basic JavaScript program which changes the background color when a button is pressed.

When I place this JS code inside the 'head' tags it does NOT work but when I place it inside the 'body'开发者_运维问答 tag it does. (When placing inside body I removed window.onload)

<script>
window.onload = function(){
var para = document.getElementById("para");

function togglecolor(){
    if(para.className != "yellow") para.className = "yellow";
    else para.className = "notYellow";
}
}
</script>

Here's the HTML:

<h1 id="para" class="">Hello World! </h1>
<button onClick="togglecolor();">Press Me</button>

I am unable to understand why it does not work when places inside 'head'.


It's a scope issue. You are defining your function within another function. This means it is only accessible inside that function. Move it outside and everything should work.

<script>
function togglecolor(){
    var para = document.getElementById("para");
    if(para.className != "yellow") para.className = "yellow";
    else para.className = "notYellow";
}
</script>


Probably because of the fact that h1 tag with id="para" is not yet loaded when the javascript was executed


I think the reason is you have defined toggleColor method inside window load event hanlder. Try to move it out and try it putting the code inside head.

<script>
function togglecolor(){
    var para = document.getElementById("para")
    if(para.className != "yellow") 
        para.className = "yellow";
    else 
        para.className = "notYellow";
}
window.onload = togglecolor;
</script>


http://sandbox.phpcode.eu/g/ea6d3/3

works. change window.onload to $(function(){

<html>
<body>
<style>
.yellow {color:yellow;}
.notYellow {color:blue;}
</style>
<script>
function togglecolor(){
        var para = document.getElementById("para");
        if(para.className != "yellow") 
             para.className = "yellow";
        else para.className = "notYellow";
}

</script>
</head>
<body>
<h1 id="para" class="notYellow">Hello World! </h1>
<button onClick="togglecolor();">Press Me</button>
</body>
</html>


The reason is probably due to your placement of the script. When a script is loaded, it is run at that point; ergo, if you have a html file like so:

 <html>
   <head />
   <body>
     <script />
     <h1 />
     <button />
   </body>
 </html>

The script file is going to be run, then the rest of the page will continue to load. Because you have the assignment of para occuring outside the context of your togglecolor function, it obtains it's value when loaded; potentially before the actual HTML element has been loaded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜