为什么我的javascript中的document.body为null? [英] Why is document.body null in my javascript?
问题描述
为什么Chrome控制台注意到这个错误:
Uncaught TypeError:Can not call method'appendChild'of
null
?
< html>
< head>
< title> Javascript测试< /标题>
< script type =text / javascript>
var mySpan = document.createElement(span);
mySpan.innerHTML =这是我的跨度!;
mySpan.style.color =red;
document.body.appendChild(mySpan);
alert(为什么在此警报后跨度发生变化?以前没有?);
< / script>
< / head>
< body>
< / body>
< / html>
此时尚未定义正文。一般来说,在执行使用这些元素的javascript之前,您希望创建所有元素。在这种情况下,您在使用 body
的头部
部分中有一些javascript。不是很酷。
你想把这段代码包装在 window.onload
处理程序中,或者将它放在之后< body>
标记(如 e-bacho 2.0 )。
< head>
< title> Javascript测试< /标题>
< script type =text / javascript>
window.onload = function(){
var mySpan = document.createElement(span);
mySpan.innerHTML =这是我的跨度!;
mySpan.style.color =red;
document.body.appendChild(mySpan);
alert(为什么在此警报后跨度发生变化?以前没有?);
}
< / script>
< / head>
查看演示。
Here is my brief HTML document.
Why is Chrome Console noting this error:
"Uncaught TypeError: Cannot call method 'appendChild' of
null
"?
<html>
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</head>
<body>
</body>
</html>
The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head
section that uses body
. Not cool.
You want to wrap this code in a window.onload
handler or place it after the <body>
tag (as mentioned by e-bacho 2.0).
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
window.onload = function() {
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
}
</script>
</head>
这篇关于为什么我的javascript中的document.body为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!