搜尋

首頁  >  問答  >  主體

類型錯誤:無法設定屬性「textContent」使用 textContent 時為 null

let firstCard = 10;
let secondCard = 4;
let sum = firstCard + secondCard;
let hasBlackJack = false;
let isAlive = true;
let message = ""
let messageEl = document.getElementById("message-el");
let sumEl = document.querySelector("#sum-el");
let cardsEl = document.getElementById("cards-el");
messageEl.textContent = "Do you want to draw a new card?";

function startGame() {
    cardsEl.textContent = "Cards : " + firstCard + " " + secondCard;
    sumEl.textContent = "Sum :" + sum;
    if (sum <= 20) {
        message = "Do you want to draw a new card?";
    } else if (sum === 21) {
        message = "You have got blackjack!";
        hasBlackJack = ture;
    } else {
        message = "You are out of the game!";
        isAlive = false;
    }
    messageEl.textContent = message;
}

P粉310754094P粉310754094453 天前512

全部回覆(1)我來回復

  • P粉969666670

    P粉9696666702023-09-08 16:32:36

    這一行:

    let messageEl = document.getElementById("message-el");

    沒有回傳元素。

    這是因為在程式碼執行時,該元素在 DOM 中不存在。這可能是因為您沒有任何具有該 ID 的元素,或者因為您需要在將該元素解析到 DOM 後移動程式碼來執行。

    回覆
    0
  • 取消回覆