【问题标题】:Can anyone tell me what's keeping this code from rendering correctly? I feel so close谁能告诉我是什么让这段代码无法正确呈现?我感觉如此接近
【发布时间】:2020-04-25 00:31:34
【问题描述】:
  1. 浏览器告诉我问题可能出在 checkForMatch() 和 FlipCard 上
  2. 具体来说,它说 cardId 是未定义的。

    const cards = [
        {
            rank: "queen",
            suite: "hearts",
            cardImage: "images/queen-of-hearts.png"
        },
        {
            rank: "queen",
            suite: "diamonds",
            cardImage: "images/queen-of-diamonds.png"
        },
        {
            rank: "king",
            suite: "hearts",
            cardImage: "images/king-of-hearts.png"
        },
        {
            rank: "king",
            suite: "diamonds",
            cardImage: "images/king-of-diamonds.png"
        }
    ];
    
    
    let cardsInPlay = [];
    
    function checkForMatch() {
        this.setAttribute('src', cards[cardId].cardImage);
        if (cardsInPlay.length === 2) {
            if (cardsInPlay[0] === cardsInPlay[1]) {
                console.log("You found a match!");
            } else {
                console.log("Sorry, try again.");
            }
        }
    }
    
    function flipCard() {
        const cardId = this.getAttribute('data-id');
        console.log("User flipped " + cards[cardId].rank);
        console.log(cards[cardId].cardImage);
        console.log(cards[cardId].suite);
        cardsInPlay.push(cards[cardId].rank);
        checkForMatch();
    }
    
    
    function createBoard() {
        for (let i = 0; i < cards.length; i++) {
            let 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();
    

【问题讨论】:

  • 当你调用一个函数时,被调用的函数不会继承调用者中可用的变量。查看 parameters 以获取从 flipCard 到 checkForMatch 的 cardId 的值。

标签: javascript function object


【解决方案1】:

您需要将cardId 变量作为参数从flipCard 函数传递到checkForMatch 函数。

所以在flipCard函数结束时你需要做的:

checkForMatch(cardId);

并且在 checkForMatch 函数声明中(就在函数的顶部),您需要这样做:

function checkForMatch(cardId) {

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 2013-05-29
  • 2017-09-15
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多