开发者

onload event on document.body behaving strange

I am using firefox 4.0 and when i use load event on the body element it behaves strange. i have tried some things and some work and some dont. the first is like this

<html>
<head>
<script type="text/javascript">
var load = function(){
alert("body loaded");      //alert not displayed
};
document.body.addEventListener("load",load,false);
</script>
</head>
<body >
</body>
</html>

now this doesnt work now i tried this

     html>
    <he开发者_JAVA百科ad>
    <script type="text/javascript">
    var load = function(){
    alert("body loaded");      //alert displayed
    };
    </script>
    </head>
    <body onload="load()">
    </body>
    </html>

this works now i tried this

<html>
<head>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</head>
<body >
</body>
</html>

this doesnt work. Whats wrong?

as response to Doug D i tried this

<html>
<head>
</head>
<body>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</body>
</html>

this doesnt work either neither does this work

<html>
<head>
</head>
<body>
</body>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</html>

in the last attempt the body has finished loadingand in the second last attempt body is being loaded. but this does not work still


The body can't be accessed in the head until it has been loaded. Your second technique of using the onload attribute is correct. Alternately, I would recommend using jQuery with

$(document).ready(function()
{
    alert("body loaded");
});

It is cross-browser compatible. Without jQuery you would need to deal with DOM event differences between IE and others.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜