Начинающий получает addEventListener не является функцией; нет JQuery

1

Я супер новичок и успешно использовал addEventListener раньше, но по какой-то причине он генерирует ошибку "addEventListener is not function" в Chrome прямо сейчас. Здесь мой рабочий файл JS:

const cards = document.getElementsByClassName('card');
const cardList = ['fa-anchor','fa-bicycle','fa-bolt','fa-bomb','fa-cube', 'fa-diamong','fa-leaf','fa-paper-plane-o']
// Log starting variables
let moves = 0;
let matchesFound = 0;
let openList = [];
let matches = 0;
let counter = 0;
let rating = 3;
let timer = {
    seconds: 0,
    minutes: 0,
}
/*
 * Display the cards on the page
 *   - shuffle the list of cards using the provided "shuffle" method below
 *   - loop through each card and create its HTML
 *   - add each card HTML to the page
 */
//Generate a new game by shuffling the cards
function newGame(){
    for (var i=0; i < 2; i++){
        cardList = shuffle(cardList);
    }
}    

// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
    var 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;
}
/*
 * set up the event listener for a card. If a card is clicked:
 *  - display the card symbol (put this functionality in another function that you call from this one)
 *  - add the card to a *list* of "open" cards (put this functionality in another function that you call from this one)
 *  - if the list already has another card, check to see if the two cards match
 *    + if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one)
 *    + if the cardaddEventListeners do not match, remove the cards from the list and hide the card symbol (put this functionality in another function that you call from this one)
 *    + increment the move counter and display it on the page (put this functionality in another function that you call from this one)
 *    + if all cards have matched, display a message with the final score (put this functionality in another function that you call from this one)
 */
cards.addEventListener('click', function() {
    console.log('Success!');
});    

//Runs timer    

//Clears timer    

//Display card symbol
function displayCard(){
    card.addClass('open show');
};    

//Add card to list of open cards
function openCard (){
};    

//Check for matches in open list
function checkMatch(){
    if (openList.length === 2) { //Make sure only two cards are open
        if (openList[0] == openList[1]){ //Check that they're the same
            lockMatch(); //Remove open and show classes, add match class
            matchesFound.push(openList[0]); //Push the matched name to the list of matches found
        }
    }
};    

//If match, lock in open position
function lockMatch(){
    card.removeClass('open show');
    card.addClass('match');
};    

//If not a match, return to closed state
function noMatch(){
};    

//Increment move counter
function incrementCounter(){
};    

//If all cards are matched & open, display win message
function winMessage(){
};

Вот связанный HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Matching Game</title>
    <meta name="description" content="">
    <link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
    <link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda">
    <link rel="stylesheet" href="css/app.css">
</head>
<body>    

    <div class="container">
        <header>
            <h1>Matching Game</h1>
        </header>    

        <section class="score-panel">
            <ul class="stars">
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
            </ul>    

            <span class="moves">3</span> Moves    

            <div class="restart">
                <i class="fa fa-repeat"></i>
            </div>
        </section>    

        <ul class="deck">
            <li class="card">
                <i class="fa fa-diamond"></i>
            </li>
            <li class="card">
                <i class="fa fa-paper-plane-o"></i>
            </li>
            <li class="card match">
                <i class="fa fa-anchor"></i>
            </li>
            <li class="card">
                <i class="fa fa-bolt"></i>
            </li>
            <li class="card">
                <i class="fa fa-cube"></i>
            </li>
            <li class="card match">
                <i class="fa fa-anchor"></i>
            </li>
            <li class="card">
                <i class="fa fa-leaf"></i>
            </li>
            <li class="card">
                <i class="fa fa-bicycle"></i>
            </li>
            <li class="card">
                <i class="fa fa-diamond"></i>
            </li>
            <li class="card">
                <i class="fa fa-bomb"></i>
            </li>
            <li class="card">
                <i class="fa fa-leaf"></i>
            </li>
            <li class="card">
                <i class="fa fa-bomb"></i>
            </li>
            <li class="card open show">
                <i class="fa fa-bolt"></i>
            </li>
            <li class="card">
                <i class="fa fa-bicycle"></i>
            </li>
            <li class="card">
                <i class="fa fa-paper-plane-o"></i>
            </li>
            <li class="card">
                <i class="fa fa-cube"></i>
            </li>
        </ul>
    </div>    

    <script src="js/app.js"></script>
</body>
</html>

Помогите?

(FWIW, я пытаюсь создать событие, которое показывает символ при щелчке по одной из карт. Этот код является WIP, но я не могу пройти мимо этой ошибки. Я также НЕ МОГУ использовать jQuery для этого.)

  • 0
    cards - это HTMLCollection элементов, но вы можете прикреплять прослушиватели событий только к отдельным элементам. Вам нужно сделать, например, cards.forEach(card => card.addEventListener(...)); или, в качестве альтернативы, присоедините один приемник событий к элементу контейнера и запросите event.target для карты.
  • 0
    Спасибо! Это отлично сработало и объяснило, где я ошибся.
Теги:

1 ответ

0
Лучший ответ

document.getElementsByClassName('card'); reutrns list элементов, которые содержат card имени класса. Поэтому, чтобы установить onclick eventlistener для каждого из элементов, используйте цикл for следующим образом:

for(var i=0; i < cards.length; i++)
{
  cards[i].onclick = function()
  {
    console.log('Success!');
  }
}   

Вот код:

const cards = document.getElementsByClassName('card');
const cardList = ['fa-anchor','fa-bicycle','fa-bolt','fa-bomb','fa-cube', 'fa-diamong','fa-leaf','fa-paper-plane-o']
// Log starting variables
let moves = 0;
let matchesFound = 0;
let openList = [];
let matches = 0;
let counter = 0;
let rating = 3;
let timer = {
    seconds: 0,
    minutes: 0,
}
/*
 * Display the cards on the page
 *   - shuffle the list of cards using the provided "shuffle" method below
 *   - loop through each card and create its HTML
 *   - add each card HTML to the page
 */
//Generate a new game by shuffling the cards
function newGame(){
    for (var i=0; i < 2; i++){
        cardList = shuffle(cardList);
    }
}    

// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
    var 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;
}
/*
 * set up the event listener for a card. If a card is clicked:
 *  - display the card symbol (put this functionality in another function that you call from this one)
 *  - add the card to a *list* of "open" cards (put this functionality in another function that you call from this one)
 *  - if the list already has another card, check to see if the two cards match
 *    + if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one)
 *    + if the cardaddEventListeners do not match, remove the cards from the list and hide the card symbol (put this functionality in another function that you call from this one)
 *    + increment the move counter and display it on the page (put this functionality in another function that you call from this one)
 *    + if all cards have matched, display a message with the final score (put this functionality in another function that you call from this one)
 */
for(var i=0; i < cards.length; i++)
{
  cards[i].onclick = function() 
  {
    console.log('Success!');
  }
}   

//Runs timer    

//Clears timer    

//Display card symbol
function displayCard(){
    card.addClass('open show');
};    

//Add card to list of open cards
function openCard (){
};    

//Check for matches in open list
function checkMatch(){
    if (openList.length === 2) { //Make sure only two cards are open
        if (openList[0] == openList[1]){ //Check that they're the same
            lockMatch(); //Remove open and show classes, add match class
            matchesFound.push(openList[0]); //Push the matched name to the list of matches found
        }
    }
};    

//If match, lock in open position
function lockMatch(){
    card.removeClass('open show');
    card.addClass('match');
};    

//If not a match, return to closed state
function noMatch(){
};    

//Increment move counter
function incrementCounter(){
};    

//If all cards are matched & open, display win message
function winMessage(){
};
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Matching Game</title>
    <meta name="description" content="">
    <link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
    <link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda">
    <link rel="stylesheet" href="css/app.css">
</head>
<body>    

    <div class="container">
        <header>
            <h1>Matching Game</h1>
        </header>    

        <section class="score-panel">
            <ul class="stars">
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
            </ul>    

            <span class="moves">3</span> Moves    

            <div class="restart">
                <i class="fa fa-repeat"></i>
            </div>
        </section>    

        <ul class="deck">
            <li class="card">
                <i class="fa fa-diamond"></i>
            </li>
            <li class="card">
                <i class="fa fa-paper-plane-o"></i>
            </li>
            <li class="card match">
                <i class="fa fa-anchor"></i>
            </li>
            <li class="card">
                <i class="fa fa-bolt"></i>
            </li>
            <li class="card">
                <i class="fa fa-cube"></i>
            </li>
            <li class="card match">
                <i class="fa fa-anchor"></i>
            </li>
            <li class="card">
                <i class="fa fa-leaf"></i>
            </li>
            <li class="card">
                <i class="fa fa-bicycle"></i>
            </li>
            <li class="card">
                <i class="fa fa-diamond"></i>
            </li>
            <li class="card">
                <i class="fa fa-bomb"></i>
            </li>
            <li class="card">
                <i class="fa fa-leaf"></i>
            </li>
            <li class="card">
                <i class="fa fa-bomb"></i>
            </li>
            <li class="card open show">
                <i class="fa fa-bolt"></i>
            </li>
            <li class="card">
                <i class="fa fa-bicycle"></i>
            </li>
            <li class="card">
                <i class="fa fa-paper-plane-o"></i>
            </li>
            <li class="card">
                <i class="fa fa-cube"></i>
            </li>
        </ul>
    </div>    

    <script src="js/app.js"></script>
</body>
</html>
  • 0
    Спасибо! Это отлично сработало и объяснило, где я ошибся.
  • 0
    @mcpherk Добро пожаловать, рад, что смог помочь :) Пожалуйста, отметьте мой ответ как принятый, поскольку он решил вашу проблему. Спасибо

Ещё вопросы

Сообщество Overcoder
Наверх
Меню