我下面的简单纸牌游戏不会显示第二张卡之前的图片继续显示警告信息,然后立即重置其游戏板。有人能帮忙吗?
此外,我对编码有点新意,可能有人帮助指出我可以改进的代码区域吗?
var cards = ['queen', 'queen', 'king', 'king'];
var cardsInPlay = [];
var gb = document.getElementById('game-board');
//allows me to compare the pushed elements in the array cardsInPlay and erase all innerHTML when its done
var isMatch = function () {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert('You found a match!');
} else {
alert('Sorry, try again.')
};
document.getElementsByClassName('card')[0].innerHTML = "";
document.getElementsByClassName('card')[1].innerHTML = "";
document.getElementsByClassName('card')[2].innerHTML = "";
document.getElementsByClassName('card')[3].innerHTML = "";
};
//pushes the 'data-card-' of a card upon an eventlistener and "flip"/show the cards image based on its 'data-card' info. triggers function check if cards are a match.
var isTwoCards = function () {
cardsInPlay.push(this.getAttribute('data-card'));
if (this.getAttribute('data-card') === 'king') {
this.innerHTML = '<img src="kingcard.png" alt="King" />'
} else {
this.innerHTML = '<img src="queencard.png" alt="Queen" />'
};
if (cardsInPlay.length === 2) {
isMatch(cardsInPlay);
cardsInPlay = [];
};
};
//iterates and creates cards, while setting an attribute and eventListener
var createCards = function () {
for (var i = 0; i < cards.length; i++) {
var children = document.createElement('div');
children.className = 'card';
gb.appendChild(children);
document.getElementsByClassName('card')[i].setAttribute('data-card', cards[i]);
document.getElementsByClassName('card')[i].addEventListener('click', isTwoCards);
};
};
createCards();