为什么不显示API的内容?

时间:2019-06-16 23:49:14

标签: javascript html api debugging

我正在尝试显示API的内容,但是由于某种原因,我在控制台中遇到一个错误,提示“ Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null”对我来说是没有意义的,因为我已将{{ 1}}。

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

这是我的html

innerHTML = <p>${this.items[i]}</p>

这是我的JavaScript

<!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>

2 个答案:

答案 0 :(得分:1)

尝试console.log列表变量。您将看到它为空。您正在将该变量视为对象,但是变量的内容为null。

答案 1 :(得分:1)

您的问题是BaseballStats的list成员为空。这是因为您正在滥用document.querySelector-它的选择方式与CSS相同,因此要选择具有类的元素,您需要使用.选择器-https://www.w3schools.com/cssref/css_selectors.asp
但是,您正在选择'baseball',这意味着它正在尝试查找标签名称为<baseball>的元素。将其更改为'.baseball',它将起作用