javascript - 类型错误 : Cannot read property 'addEventListener' of null at game. js:51

标签 javascript html

我尝试使用 window.onload = fuction () {}; 没有得到积极的结果...
当我去玩(这是另一个 html game.html)并且出现该错误时,就会发生错误。该应用程序的想法是选择测验的类别和难度(它是一个 API),我得到了数组,但在按下 PLAY 的那一刻,它抛出了我提到的错误。

git 中的应用程序 URL:https://gitlab.com/silvatapialuis/quiz-app

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Open Trivia</title>
    <link rel="stylesheet" href="app.css" />
    <link href="/favicon.ico" type="image/x-icon" rel="icon" />
  </head>
  <body>
    <div class="container">
      <div id="home" class="flex-center flex-column">
        <h1>Open Trivia</h1>
        <h5>Select Category:</h5>
        <button id="fetch">FETCH URL</button>
        <form name="formul1" class="cont">
          <select id="cat" name="cat" onchange="selectCat()">
            <option value="">Any Category</option>
            <option value="&category=9">General Knowledge</option>
            <option value="&category=10">Entertaiment: Books</option>
            <optiseon value="&category=11">Entertaiment: Film</option>
              <option value="&category=12">Entertaiment: Music</option>
              <option value="&category=13">Entertaiment: Musicals & Theatres</option>
              <option value="&category=14">Entertaiment: Television</option>
              <option value="&category=15">Entertaiment: Video Games</option>
              <option value="&category=16">Entertaiment: Board Games</option>
                                            .
                                            .
                                            .
          </select>
        </form>
        <h5>Select Difficulty:</h5>
        <form name="formul2" class="cont">
          <select id="diff" name="diff" onchange="selectDiff()">
            <option value="">Any Difficulty</option>
            <option value="&difficulty=easy">Easy</option>
            <option value="&difficulty=medium">Medium</option>
            <option value="&difficulty=hard">Hard</option>
          </select>
        </form>
        <a class="btn" href="/game.html">Play</a>
        <a class="btn" href="/highscores.html">High Scores</a>
      </div>
    </div>
    <script src="game.js"></script>
  </body>
</html>

game.js

//点击事件按钮

var btnFetch = document.getElementById('fetch');

/*Line 51*/btnFetch.addEventListener('click', function(e) {
  console.log('Would fetch newUrl:', newUrl);
  fetch(newUrl)
    .then(res => {
      return res.json();
    })
    .then(loadedQuestions => {
      console.log(loadedQuestions.results);
      questions = loadedQuestions.results.map(loadedQuestion => {
        const formattedQuestion = {
          question: loadedQuestion.question
        };

        const answerChoices = [...loadedQuestion.incorrect_answers];
        formattedQuestion.answer = Math.floor(Math.random() * 3) + 1;
        answerChoices.splice(
        formattedQuestion.answer - 1,
        0,
        loadedQuestion.correct_answer
        );
        answerChoices.forEach((choice, index) => {
          formattedQuestion["choice" + (index + 1)] = choice;
        });

        return formattedQuestion;
      });

                               .
                               .
                               .
});

game.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Quick Quiz - Play</title>
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="game.css" />
  </head>
  <body>
    <div class="container">      
      <div id="loader"></div>
      <div id="game" class="justify-center flex-column hidden">
        <div id="hud">
          <div id="hud-item">
            <p id="progressText" class="hud-prefix">
              Question
            </p>
            <div id="progressBar">
              <div id="progressBarFull"></div>
            </div>
          </div>
          <div id="hud-item">
            <p class="hud-prefix">
              Score
            </p>
            <h1 class="hud-main-text" id="score">
              0
            </h1>
          </div>
        </div>
        <h2 id="question"></h2>
        <div class="choice-container">
          <p class="choice-prefix">A</p>
          <p class="choice-text" data-number="1"></p>
        </div>
        <div class="choice-container">
          <p class="choice-prefix">B</p>
          <p class="choice-text" data-number="2"></p>
        </div>
        <div class="choice-container">
          <p class="choice-prefix">C</p>
          <p class="choice-text" data-number="3"></p>
        </div>
        <div class="choice-container">
          <p class="choice-prefix">D</p>
          <p class="choice-text" data-number="4"></p>
        </div>
      </div>
    </div>
    <div class="container1">
      <a class="btn" href="/">Go Home</a>
    </div>
    <script src="game.js"></script>
  </body>
</html>

最佳答案

问题是 document.getElementById('fetch')没有产生任何结果,所以我的第一个猜测是,执行代码时该元素不在页面上。

如果在浏览器有机会解析该元素之前执行 JS 代码,则可能会发生这种情况,但根据您的代码,我大胆猜测包括 <html> 之外的脚本标签是你的问题。尝试将其作为 <body> 的最后一个子项标签,就在 </body> 之前.

放置 <script>收盘前<body>确保浏览器在运行 JS 之前已解析所有 HTML。

关于javascript - 类型错误 : Cannot read property 'addEventListener' of null at game. js:51,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861544/

相关文章:

javascript - Node.js package.json 是否需要位于存储库的根目录?

javascript - Reactjs - Web 应用程序需要运行时权限吗?

javascript - PhoneGap/ Cordova : Google Maps API - drop pin on my position

php - jQuery AJAX POST 到 mysql 表以获取动态表数据-我是否以正确的方式执行此操作?

html - 创建两个中间没有空格的按钮

javascript - AngularJS - 如何在 JS 中加载绑定(bind)到的变量之前不显示 HTML 元素?

javascript - JSON 理解和数组

javascript - JSON 到客户端的 ASP.NET 脚本服务的字符串?

javascript - 以标准尺寸渲染图像,无需拉伸(stretch),具有最小尺寸

javascript - 使用 jQuery 增加和减少页面的比例