我是JavaScript的新手,我正试图找出错误的地方

时间:2017-11-22 14:57:20

标签: javascript

  

我一直收到这个错误,我不知道该怎么办?我试着       制作翻转卡片游戏。       未捕获的TypeError:无法读取未定义的属性'getAttribute'       在flipCard(main.js:42)       在createBoard(main.js:53)       在main.js:59

var cards = [
    {
    rank: 'queen',
    suit: 'diamonds',
    cardImage: 'images/queen-of-diamonds.png'
    },
    {
    rank: 'queen',
    suit: 'hearts',
    cardImage: 'images/queen-of-hearts.png'
    },
    {
    rank: 'king',
    suit: 'diamonds',
    cardImage: 'images/king-of-diamonds.png'
    },
    {
    rank: 'king',
    suit: 'hearts',
    cardImage: 'images/king-of-hearts.png'
    }
    ]
    var cardsInPlay = [cards]
    var checkForMatch = function () {
    this.cardImage.setAttribute(src)
    if (cardsInPlay[0] === cardsInPlay[1]) {
    window.alert('You found a match!')
    } else {
    window.alert('Sorry, try again')
    }
    }

var flipCard = function (cardId) {
this.cardId.getAttribute('data-id')
checkForMatch()
console.log('User flipped ' + cards[cardId].rank)
console.log('User flipped ' + cards[cardId].cardImage)
console.log('User flipped ' + cards[cardId].suit)
}
function 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())
cardElement.appendChild(game-board)
}
}
createBoard()
cardsInPlay.push(cards[cardId])`

2 个答案:

答案 0 :(得分:1)

这里:

cardElement.addEventListener('click', flipCard())

你正在调用flipCard而不是传递函数引用。 尝试相应地更改代码

var flipCard = function(cardId) {
  //no need of 'this' here
  cardId.getAttribute('data-id')
  checkForMatch()
  console.log('User flipped ' + cards[cardId].rank)
  console.log('User flipped ' + cards[cardId].cardImage)
  console.log('User flipped ' + cards[cardId].suit)
}

function 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.bind(null, cardElement))
    cardElement.appendChild(game-board)
  }
}

答案 1 :(得分:0)

checkForMatch中没有this值,因为它是在全局空间中定义的,而您直接调用它。您可能希望使用callhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

来调用它
checkForMatch.call(this);