[英]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. 我正在使用firefox 4.0,当我在body元素上使用load事件时,它的行为很奇怪。 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>
<head>
<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 作为对道格D的回应,我尝试了这个
<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 loading
and in the second last attempt body is being loaded
. 在最后一次尝试中,
body has finished loading
而在第二次尝试中, body is being loaded
。 but this does not work still 但这仍然无法正常工作
The body
can't be accessed in the head until it has been loaded. 在加载之前,无法在头部访问
body
。 Your second technique of using the onload attribute is correct. 使用onload属性的第二种技术是正确的。 Alternately, I would recommend using jQuery with
或者,我建议将jQuery与
$(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.
没有jQuery,您将需要处理IE与其他人之间的DOM事件差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.