gpt4 book ai didi

javascript - 为什么API的内容显示不出来?

转载 作者:行者123 更新时间:2023-11-30 13:59:25 25 4
gpt4 key购买 nike

我正在尝试显示 API 的内容,但出于某种原因,我在控制台中收到错误消息 Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null哪种类型对我来说没有意义,因为我已经设置为 innerHTML = <p>${this.items[i]}</p> .

我做错了什么,我该如何解决?如果您需要更多信息,请告诉我。

这是我的html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>

<div class="baseball">
<h1>test</h1>
</div>

<script type="application/javascript" src="index.js"></script>
<script type="text/javascript">
window.addEventListener("load", function() {
console.log("document is loaded");

var baseballStats = new BaseballStats();

baseballStats.init("https://statsapi.mlb.com/api/v1/people/660670/stats?stats=byDateRange&season=2018&group=hitting&startDate=&endDate=&leagueListId=mlb_milb", true);
});
</script>
</body>
</html>

这是我的javascript

class BaseballStats {
constructor() {
this.totalItems = 0;
this.list = document.querySelector("baseball");
}

init(url, bool) {
this.bool = bool;

var that = this;

console.log(url);

fetch(url)
.then(resp => resp.json())
.then(data => {
console.log(data.stats);

that.data = data;

if (this.bool) {
that.items = that.data.stats;
this.totalItems = that.items.length;

console.log("about to loop");

for (var i = 0; i < this.totalItems; i++) {
var listNode = document.createElement("LI");

listNode.innerHTML = `<p>${this.items[i]}</p>`;
console.log("did it reach here");

this.list.appendChild(listNode);
}
}
});
}
}

最佳答案

尝试 console.log 列表变量。你会看到它是空的。您将此变量视为对象,但变量的内容为空。

关于javascript - 为什么API的内容显示不出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56623415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com