[英]Cannot read property 'innerHTML' of null error. My script is at the end of the body, why am I still getting this error?
My script is at the end of the body, which has been the basic answer I've seen given when searching for a solution.我的脚本在正文的末尾,这是我在寻找解决方案时看到的基本答案。 What am I doing wrong?我究竟做错了什么? Do I need to use async/await?我需要使用异步/等待吗? I've written almost this exact code before, and its worked.我以前写过几乎这个确切的代码,并且它起作用了。
HTML: HTML:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body id="body">
<h1 id="header">Pokemon</h1>
<div id="main-container">
</div>
<button id="button">Click</button>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
JS: JS:
let pokemon = document.querySelectorAll('.poke');
let button = document.getElementById('button');
let container = document.getElementById('main-container');
function loadPokemon() {
const urs = 'https://pokeapi.co/api/v2/pokemon';
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
const poke = JSON.parse(xhr.responseText)
container.innerHTML+= `
${poke.results.map(function(pok, index) {
return `
<div class='poke'>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png">
</img>
${pok.name}
</div>
`
})}
`
}
}
xhr.open('GET', urs, true);
xhr.send();
};
button.addEventListener('click', loadPokemon);
It is working here.. I did not make any changes to your code它在这里工作..我没有对您的代码进行任何更改
let pokemon = document.querySelectorAll('.poke'); let button = document.getElementById('button'); let container = document.getElementById('main-container'); function loadPokemon() { const urs = 'https://pokeapi.co/api/v2/pokemon'; let xhr = new XMLHttpRequest(); xhr.onload = function() { if(xhr.status === 200) { const poke = JSON.parse(xhr.responseText) container.innerHTML+= ` ${poke.results.map(function(pok, index) { return ` <div class='poke'> <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png"> </img> ${pok.name} </div> ` })} ` } } xhr.open('GET', urs, true); xhr.send(); }; button.addEventListener('click', loadPokemon);
<!DOCTYPE html> <html> <head> <title>Index</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body id="body"> <h1 id="header">Pokemon</h1> <div id="main-container"> </div> <button id="button">Click</button> <script type="text/javascript" src="ajax.js"></script> </body> </html>
Your code is working fine.您的代码运行良好。 Are you sure you copy and pasted the exact code?您确定复制并粘贴了确切的代码吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.