记忆游戏-如何得到两个卡图像显示之前的警报弹出

Memory Game - how to get both card images to display before the alert pops

本文关键字:显示 图像 两个 何得 记忆游戏      更新时间:2023-09-26

我用JavaScript编写了一个内存游戏的代码。我的问题是,我不能弄清楚为什么这两张牌选择不显示警报之前(说,万岁,他们是相同的/不,他们不匹配)弹出。我很困惑,因为警报是在isMatch函数中,这是在两张卡被点击后运行的(isTwoCards函数)。

var isTwoCards = function(){
    if (this.getAttribute('data-card') === 'king') {
        this.innerHTML = '<img src="King.png" class = "myImgClass" alt="King"/>';   
    } else {
        this.innerHTML = '<img src="Queen.png" class = "myImgClass" alt="Queen" />';
    }
    cardsInPlay.push(this.getAttribute('data-card'));
    if (cardsInPlay.length === 2) {
        isMatch(cardsInPlay);
    }
};
var isMatch = function() {
    if (cardsInPlay[0] !== cardsInPlay[1]) {
        alert('Sorry, try again.');
        cardElement.className = "";
    } else {
        alert('You found a match!')
    };
    cardsInPlay = [];
}

完整代码如下:http://codepen.io/Lupeman/pen/GNgXrm

任何帮助都将非常感激,因为它快把我逼疯了!我不想使用JQuery

您可能希望延迟isMatch检查,直到UI完成更新并且用户已经完成鼠标向上。

if (cardsInPlay.length === 2) {
    setTimeout(function() {
        isMatch(cardsInPlay);
    }, 1000);
}