简体   繁体   中英

Why does my for loop start with the last item and stops running after one iteration?

My question is in reference to the createBoard() function, the second function here.

When executed the loop starts with the last item in the [cards] array. It assigns "king" to the first <.card class element> and then the loop stops. Any insight here?

main.js

function createCards(){

var gameBoard = document.getElementById('game-board');

for(var i = 1; i <= 4; i++){

  //Create newCard as a Div 

    var newCard = document.createElement('div');

  //Add Class of .card to the NewCard   
    newCard.className = 'card';

  // Append card to the board   
    gameBoard.appendChild(newCard);
    }
}


createCards();




var cardsInPlay = [];

function createBoard() {

    var cards = ["queen", "queen", "king", "king"];

    for(var j = 0; j < cards.length; j++){

     document.querySelector(".card").setAttribute("data-card", cards[j]);

    // document.querySelector(".card").addEventListener("click", isTwoCards)
    }
}


createBoard();

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Memory Game</title>

 <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

<nav class="clearfix">

<a href="#">Instructions</a>
<a href="#">Game</a>

</nav>

<h1>Memory Game</h1>
<h2>This is a game of "Remember This"</h2>

<h2>Instructions</h2>


<p>Concentration,....more text</p>


  <div class="board" id="game-board">

  </div>






<footer>


</footer>
<script src="main.js"></script>
</body>
</html>

Your for loop doesn't start at the last element, it just override the value you already have there.

By using the setAttribute function over and over - you override the value (and the last value you set is the one you you have.

I'm not sure what is your desired outcome here, but you can set the value to be the old one combined with the new one:

for(var j = 0; j < cards.length; j++){
    document.querySelector(".card").setAttribute("data-card", document.querySelector(".card").getAttribute("data-card") + cards[j]);
}

for example.

You are overriding here. You can follow this simple step by separating from the loop.

function createBoard() {

    var cards = ["queen", "queen", "king", "king"];
    var cardArr = document.getElementsByClassName("card");
    for(var j = 0; j < cards.length; j++){

    cardArr[j].setAttribute("data-card", cards[j]);
    }
}

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM