insertAdjacentHTML无法读取null属性

时间:2017-10-20 12:38:25

标签: javascript json ajax

以下错误不断重复...我只想解释这里有什么问题和一些提示

错误

script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
at renderHTML (script.js:20)
at XMLHttpRequest.ourRequest.onload (script.js:13)

的javascript

var animalContainer=_('animal-info');
function _(id){

    return document.getElementById(id);

}

_('btn').addEventListener("click",function(){
    var ourRequest=new XMLHttpRequest();
ourRequest.open('GET','test.json');
    ourRequest.onload=function(){
        var ourData=JSON.parse(ourRequest.responseText);
        renderHTML(ourData);
        console.log(ourData[0]);
    };
ourRequest.send();
});

function renderHTML(data){
     animalContainer.insertAdjacentHTML('beforeend','testing 123');
}

的index.php

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>


    <button id ="btn">Submit</button>
<script type="text/javascript" src="script.js"></script>


<div id="animal-info"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要在 renderHTML()函数内声明 animalContainer 变量,或将其作为参数传递。