以下错误不断重复...我只想解释这里有什么问题和一些提示
script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
at renderHTML (script.js:20)
at XMLHttpRequest.ourRequest.onload (script.js:13)
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');
}
<!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>
答案 0 :(得分:0)
您需要在 renderHTML()函数内声明 animalContainer 变量,或将其作为参数传递。