简体   繁体   English

为什么我的javascript中的document.body为null?

[英]Why is document.body null in my javascript?

Here is my brief HTML document. 这是我的简短HTML文档。

Why is Chrome Console noting this error: 为什么Chrome控制台会注意到此错误:

"Uncaught TypeError: Cannot call method 'appendChild' of null "? “未捕获的TypeError:无法调用null方法'appendChild'”?

<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. 通常,您希望在执行使用这些元素的javascript之前创建所有元素。 In this case you have some javascript in the head section that uses body . 在这种情况下,你在head使用body有一些javascript。 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 ). 要在一个包裹此代码window.onload处理程序或将其放置在 <body>标签(通过提及电子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>

See demo . 见演示

Your script is being executed before the body element has even loaded. 您的脚本在body元素加载之前正在执行。

There are a couple ways to workaround this. 有几种方法可以解决这个问题。

  • Wrap your code in a DOM Load callback: 将代码包装在DOM Load回调中:

    Wrap your logic in an event listener for DOMContentLoaded . 将您的逻辑包装在DOMContentLoaded的事件侦听器中。

    In doing so, the callback will be executed when the body element has loaded. 这样做时,将在加载body元素时执行回调。

     document.addEventListener('DOMContentLoaded', function () { // ... // Place code here. // ... }); 

    Depending on your needs, you can alternatively attach a load event listener to the window object: 根据您的需要,您也可以将load事件侦听器附加到window对象:

     window.addEventListener('load', function () { // ... // Place code here. // ... }); 

    For the difference between between the DOMContentLoaded and load events, see this question . 有关DOMContentLoadedload事件之间的区别, 请参阅此问题

  • Move the position of your <script> element, and load JavaScript last: 移动<script>元素的位置,最后加载JavaScript:

    Right now, your <script> element is being loaded in the <head> element of your document. 现在,您的<script>元素正在文档的<head>元素中加载。 This means that it will be executed before the body has loaded. 这意味着它将在body加载之前执行。 Google developers recommends moving the <script> tags to the end of your page so that all the HTML content is rendered before the JavaScript is processed. Google开发人员建议将<script>标记移动到页面末尾,以便在处理JavaScript之前呈现所有HTML内容。

     <!DOCTYPE html> <html> <head></head> <body> <p>Some paragraph</p> <!-- End of HTML content in the body tag --> <script> <!-- Place your script tags here. --> </script> </body> </html> 

Add your code to the onload event. 将代码添加到onload事件中。 The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, . 接受的答案正确地显示了这一点,但是在撰写本文时,答案以及所有其他答案也建议将脚本标记放在结束标记之后,。

This is not valid html. 这不是有效的HTML。 However it will cause your code to work, because browsers are too kind ;) 但是它会导致你的代码工作,因为浏览器太客气了;)

See this answer for more info Is it wrong to place the <script> tag after the </body> tag? 有关详细信息,请参阅此答案。 将<script>标记放在</ body>标记后面是错误的吗?

Downvoted other answers for this reason. 由于这个原因,其他答案也是如此。

Or add this part 或者添加此部分

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

after the HTML, like: 在HTML之后,如:

    <html>
    <head>...</head>
    <body>...</body>
   <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>

    </html>

Browser parses your html from top down, your script runs before body is loaded. 浏览器从上到下解析您的html,您的脚本在加载正文之前运行。 To fix put script after body. 修复身体后的脚本。

  <html>
  <head>
       <title> Javascript Tests </title> 
  </head>
 <body>
 </body>
  <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>
</html>

document.body is not yet available when your code runs. 代码运行时, document.body尚不可用。

What you can do instead: 你可以做什么:

var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM