javascript – 未捕获的TypeError:无法读取null的属性’appendChild’

前端之家收集整理的这篇文章主要介绍了javascript – 未捕获的TypeError:无法读取null的属性’appendChild’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我收到以下错误

Uncaught TypeError: Cannot read property ‘appendChild’ of null

myRequest.onreadystatechange @ script.js:20

用我的以下代码

// index.html 
<html>
    <head>
        <title>Simple Page</title>
    </head>
    <body>
        <div id="mainContent">
            <h1>This is an AJAX Example</h1>
        </div>
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

这是我的JavaScript文件

// script.js
// 1. Create the request

var myRequest;

// feature check!
if(window.XMLHttpRequest) { // Firefox,Safari
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // IE
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}


// 2. Create an event handler for our request to call back 
myRequest.onreadystatechange = function() {
    console.log("We were called!");
    console.log(myRequest.readyState);
    if(myRequest.readyState === 4){
        var p = document.createElement("p");
        var t = document.createTextNode(myRequest.responseText);
        p.appendChild(t);
        document.getElementById("mainContent").appendChild(p);
    }
};

// 3. open and send it
myRequest.open("GET","simple.txt",true);

// any parameters?
myRequest.send(null);

这是simple.txt的内容

This is the contents of a simple text file.

我把脚本标签放在html as suggested by @Tejs here底部,但我仍然收到此错误.

解决方法

在执行回调时,页面上没有带有“mainContent”的元素.

在线:

document.getElementById("mainContent").appendChild(p);

部分document.getElementById(“mainContent”)返回null

原文链接:https://www.f2er.com/js/159409.html

猜你在找的JavaScript相关文章