繁体   English   中英

为什么不显示API的内容?

[英]Why won't the contents of the API be displayed?

我正在尝试显示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 list变量。 您将看到它为空。 您将此变量视为对象,但是变量的内容为null。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM