下面是我的代碼。任何時候,我點擊一個卡,我得到的錯誤在我的控制檯:獲取錯誤'無法讀取屬性'未定義的屬性'getAttribute'
無法讀取的不確定
財產「的getAttribute」這究竟是爲什麼?
var cards = [
{
"rank": "queen",
"suit":"hearts",
"cardImage": "images/queen-of-hearts.png"
},{
"rank": "queen",
"suit":"diamonds",
"cardImage": "images/queen-of-diamonds.png"
},{
"rank": "king",
"suit":"hearts",
"cardImage": "images/king-of-hearts.png"
},{
"rank": "king",
"suit":"diamonds",
"cardImage": "images/king-of-diamonds.png"
}
]
var cardsInPlay = [];
var checkForMatch = function() {
this.setAttribute('src', this.cardImage);
if(cardsInPlay.length === 2) {
cardsInPlay[0] === cardsInPlay[1]?alert('You found a match!'):alert('Sorry, try again.');
}
}
var flipCard =() => {
var cardId = this.getAttribute('data-id');
console.log(`User flipped ${cards[cardId].rank}`);
cardsInPlay.push(cards[cardId].rank);
console.log(cards[cardId].cardImage);
console.log(cards[cardId].suit);
checkForMatch();
}
var createBoard =() => {
for (var i = 0; i < cards.length; i ++) {
var cardElement = document.createElement('img');
cardElement.setAttribute('src','images/back.png');
cardElement.setAttribute('data-id', i);
cardElement.addEventListener('click', flipCard);
document.getElementById('game-board').appendChild(cardElement);
}
}
createBoard();
謝謝你。我會做出改變。我仍然在我的flipCard()的第一行出現同樣的錯誤。 –
Kermit說什麼,箭頭功能指向父母,所以它選擇'遊戲板'。把'this'改成'cardElement' –