为什么我的 javascript 中的 document.body 为 null? [英] Why is document.body null in my javascript?

查看:22
本文介绍了为什么我的 javascript 中的 document.body 为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简短 HTML 文档.

Here is my brief HTML document.

为什么 Chrome 控制台会注意到这个错误:

Why is Chrome Console noting this error:

未捕获的类型错误:无法调用 null 的方法 'appendChild'"?

"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>

推荐答案

此时尚未定义主体.通常,您希望在执行使用这些元素的 javascript 之前创建所有元素.在这种情况下,您在使用 bodyhead 部分中有一些 javascript.不酷.

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.

您想将此代码包装在 window.onload 处理程序中或将其放在 之后 标记(如e-bacho 2.0).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆