以下是我的代码。每当我点击其中一张卡片时,我都会在控制台中收到错误:
无法读取未定义
的属性'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();
答案 0 :(得分:0)
this
指的是函数checkForMatch()
,而不是flipCard()
,这意味着如果您在this
中使用flipCard()
,则会有效,因为它指的是cardElement
。 this
内的checkForMatch()
指的是函数,不是,cardElement
。
您可以做的是将this.setAttribute('src', this.cardImage);
替换为this
假设的内容。
答案 1 :(得分:0)
你不应该使用arrow-function,因为在箭头函数中,this
指向父范围。所以this
是undefined
。使用箭头功能时应该小心。