记忆游戏如何使用设置属性翻转当前卡



我正在制作一个记忆游戏,并试图将卡片翻转到其图像值。 当我单击卡时,它应该将图像更改为数组中的当前图像,但由于某种原因,它不起作用。

.JS

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 (cardId) {
    if (faces[cardId] === faces[cardId + 1]) {
        console.log("You found a match!");
    } else {
        console.log("Sorry, try again.");
    }
}
var flipCard = function (cardId, name) {
    document.getElementById('image1')[this].getAttribute("id").src = faces[cardId]
    checkForMatch();
}

.HTML

<div>
    <img onclick="flipCard(1,this)" id="image1" src="images/back.png" alt="Queen of Diamonds">
    <img onclick="flipCard(2,this)" id="image1" 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。Id 被认为是唯一的,因此您不应该在整个页面中有更多具有相同 id 的元素。

此时您可以直接执行以下操作:

var flipCard = function (cardId, name) {
    document.getElementById('image1').src = faces[cardId];
    checkForMatch();
}

最新更新