获取错误'无法读取属性'getAttribute'未定义'

时间:2017-04-25 00:14:31

标签: javascript undefined

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

  

无法读取未定义

的属性'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();

enter image description here

2 个答案:

答案 0 :(得分:0)

您在上下文中的

this指的是函数checkForMatch(),而不是flipCard(),这意味着如果您在this中使用flipCard(),则会有效,因为它指的是cardElementthis内的checkForMatch()指的是函数,不是cardElement

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

答案 1 :(得分:0)

你不应该使用arrow-function,因为在箭头函数中,this指向父范围。所以thisundefined。使用箭头功能时应该小心。