附录中的错误 [英] Error in appendchild

查看:27
本文介绍了附录中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下非常简单的代码:

I have the following very simple code:

<html>
<head>
  <script type="text/javascript" >

    function showAlert(){
      alert("I am clicked");
    }

    function one(){
      var a1 = [1,2,3];
      for (var i=0;i<a1.length;i++) {
        var p = document.createElement('p');
        p.innerHTML = a1[i];
        p.onclick = showAlert;
        document.body.appendChild(p);
      }

      console.log("I am called");
    }

    one();   
  </script>
</head>
</html>

我遇到以下错误:未捕获的TypeError:无法读取属性'appendChild的null 。谁能告诉我,我要去哪里错了?我正在 Chrome 中进行测试。

I am getting the following error:Uncaught TypeError: Cannot read property 'appendChild' of null. Can anybody tell me, where am I going wrong? I am testing in Chrome.

推荐答案

document.body.appendChild 在定义正文之前运行,因此 document.body 仍然为 null

document.body.appendChild is run before the body is defined, hence document.body is still null.

将脚本向下移动到< body>< / body> 下使用以下命令执行

Either move this script down under the <body></body> or delay it's execution with:

window.addEventListener("load", function () { /* we're ready */ });

这篇关于附录中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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