簡體   English   中英

如何在Javascript記憶游戲中翻轉卡

[英]how to flip card in javascript memory game

我是javascript的入門者,當我單擊它時會嘗試翻轉卡片。 我在調用函數flipcard時在html中傳遞了cardid。 但是我收到一個錯誤消息,說不能將屬性src設置為null。

var faces = []; //array to store card images
     faces[0] = 'images/king-of-diamonds.png';
     faces[1] = 'images/king-of-hearts.png';
     faces[2] = 'images/queen-of-diamonds.png';
     faces[3] = 'images/queen-of-hearts.png';

var cardsInPlay = [];

var checkForMatch = function() {
    if (cardsInPlay[0] === cardsInPlay[1]) {
          console.log("You found a match!");
        } else {
            console.log("Sorry, try again.");
        }
}

var flipCard = function(cardId) {

    document.getElementById('q').src=faces[cardId]

    checkForMatch();
}






 Html



  <div>
            <img onclick="flipCard(1)" id="image1" src="images/back.png" alt="Queen of Diamonds">
            <img onclick="flipCard(2)" id="image2" src="images/back.png" alt="Queen of Hearts">
            <img id="image3" src="images/back.png" alt="King of Diamonds">
            <img id="image4" src="images/back.png" alt="King of Hearts">
        </div>

在您的代碼中查看什么是id = q?

document.getElementById('q').src=faces[cardId]

您的HTML中沒有這樣的ID,這就是為什么src為null的原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM