【发布时间】:2021-09-04 14:49:56
【问题描述】:
无法摆脱这个控制台错误:“Uncaught (in promise) TypeError: Cannot read property 'append' of null”,我对阅读其他几篇堆栈溢出文章的理解是 js 文件在 html 之前运行完成加载。我已经在索引文件关闭之前移动了右侧,并尝试通过执行以下操作来推迟 JS 文件:
document.addEventListener("DOMContentLoaded", function(event) {
// copy code here
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="utf-8">
<title>API Explorer</title>
<script src="scripts.js" defer></script>
</head>
<body>
<ul class="navbar">
<li><a href="./index.html">Home</a></li>
<li><a href="./people.html">People</a></li>
</ul>
<h1>API Explorer</h1>
<div id="data-container">
<div id="people"></div>
</div>
</body>
</html>
scripts.js:
function getDataName(url, div) {
try {
fetch(url)
.then(response => response.json())
.then(data => showDataName(data.results, div))
}
catch(error){
console.error("Error: " + error)
}
}
showDataName = (dataObjects, div) => {
const dataDiv = document.querySelector(div)
dataObjects.forEach(dataObject => {
const dataElement = document.createElement('p')
dataElement.innerText= `Name: ${dataObject.name}`
dataDiv.append(dataElement)
})
}
getDataName('https://swapi.dev/api/people/', '#people')
【问题讨论】:
-
上面写着
// copy code here...你也是吗?
标签: javascript html dom dom-events