尝试使用特定的类名来定位<i>标记

时间:2017-10-11 18:22:19

标签: javascript jquery html

所以我正在开展这个项目,我遇到的障碍是针对<i>元素中的特定<li>标记,并将其与其他特定<i>匹配另一个<li>内的元素。这是通过单击<li>元素并将值存储在数组中来选择,以检查另一个<i>标记中的匹配<li>元素。我不相信$(this).children().innerHTML是定位这些元素的正确方法。

Link to jsfiddle

以下代码:

let cards = [
    "diamond",
    "leaf",
    "cube",
    "bomb",
    "bicycle",
    "anchor",
    "paper-plane-o",
    "bolt",
    "diamond",
    "leaf",
    "cube",
    "bomb",
    "bicycle",
    "anchor",
    "paper-plane-o",
    "bolt"
],
openedCards = [],
$deck = $(".deck"),
$card = (".card"),
$scorePanel = $('#score-panel'),
$moves = $('.moves'),
$rating = $("i"),
$restart = $(".restart"),
delay = 500,
match = 0,
moves = 0,
amountOfCards = cards.length / 2,
threeStars = amountOfCards + 2,
twoStars = amountOfCards + 6,
oneStar = amountOfCards + 10;


// Shuffle function
function shuffle(array) {
    let currentIndex = array.length,
        temporaryValue, randomIndex;

    while (currentIndex !== 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

// Create the new Game

function newBoard() {
    let shuffledCards = shuffle(cards);
    $deck.empty();
    match = 0;
    moves = 0;

    for (let i = 0; i < cards.length; i++) {
        $deck.append($('<li class="card"><i class="fa fa-' + cards[i] 
+ '"></i></li>'))
    }
    cardClickListener();
};

let cardClickListener = function() {
    $deck.find('.card:not(".match, .open")').on("click", function() {
        let $this = $(this);
        let card = $this.children().innerHTML;
        $this.addClass("open show");
        openedCards.push(card);
        console.log(openedCards);

        if (openedCards.length > 1) {
             if (card === openedCards[0]) {
                 $deck.find('.open').addClass('match');
                setTimeout(function() {
                    $deck.find('.match').removeClass('open show');
                }, delay);
            }   
        }
    });
};

newBoard();

1 个答案:

答案 0 :(得分:0)

好的,我想通了。我必须用

定位我的特定卡片

let card = $(this).children("i").attr("class");

此时我能够将存储该值的卡变量推送到我的空数组中。