gpt4 book ai didi

javascript - 获取错误 'Cannot read property ' getAttribute' of undefined'

转载 作者:行者123 更新时间:2023-11-28 04:43:17 25 4
gpt4 key购买 nike

这是我的代码。每当我单击其中一张卡片时,我都会在控制台中收到错误消息:

Cannot read property 'getAttribute' of undefined

为什么会发生这种情况?

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();

enter image description here

最佳答案

this 在您的上下文中指的是函数 checkForMatch(),而不是 flipCard(),这意味着如果您要使用flipCard() 中的 this 会起作用,因为它引用了 cardElementcheckForMatch() 中的 this 引用的是函数,不是cardElement

您可以做的是将 this.setAttribute('src', this.cardImage); 替换为 this 的预期内容。

关于javascript - 获取错误 'Cannot read property ' getAttribute' of undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43599551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com