简体   繁体   中英

Adding a random class to element from an array that duplicates using jQuery

I'm creating a matching game and I'm trying to add a class from an array to match against. The code I have below creates the classes I need, then randomizes them.

My problem is in the randomizeDeck function. I'm trying to add each of the classes to the specified element twice. When I console.log the code the classes gets added to the first six elements but not the last six, which I need it to do so that I have the classes to match against in the matching game I'm creating.

var cardDeck = new Array();

function createDeck() {
    for (i = 1; i <= 6; i++) {
        cardDeck.push("card-" + i);
    }
}
createDeck();

var randDeck = cardDeck.sort(randOrd);

function randomizeDeck() {
    card.each(function(i){
        $(this).addClass(randDeck[i]);
    });
}
randomizeDeck();

I think your createDeck function needs to create 12 classes instead of 6. Just push each one twice:

function createDeck() {
    for (i = 1; i <= 6; i++) {
        cardDeck.push("card-" + i);
        cardDeck.push("card-" + i);
    }
}

Then you'll have an array of 12 classes (2 each of 6 unique classes), which will be randomized and assigned to the 12 cards.

Your randomizeDeck() function can be rewritten to use the same array of class names twice:

function randomizeDeck() {
    card.each(function(i){
        if(i < 6)
            $(this).addClass(randDeck[i])
        else
            $(this).addClass(randDeck[i-6]);
    });
}

Note: I would rewrite the variable card as $cards so that you know it's a jQuery object and in this case a collection of them. Otherwise, its hard to tell it apart from any other javascript var.

Try something like this - it's tested now updated SEE THIS FIDDLE http://jsfiddle.net/8XBM2/1/

var cardDeck = new Array();

function createDeck() {
    for (i = 1; i <= 6; i++) {
        cardDeck.push("card-" + i);
    }
}
createDeck();
var randDeck = cardDeck.sort();
alert(randDeck);

function randomizeDeck() {
    var x = 0;
    $('div').each(function(i){
     if ( i > 5) { 

                $(this).addClass(randDeck[x]);
         x++; 
      } else {
        $(this).addClass(randDeck[i]);
    }
    });
}
randomizeDeck();

I suggest a separate variable to keep track of the index, rather that the each index. Once you've gone through the pack once, it might be a good idea to shuffle the deck again so the order is different on the second pass. YMMV.

function sortCards(randOrd) {
  randDeck = cardDeck.sort(randOrd);
}

function randomizeDeck() {
  var count = 0;
  cards.each(function(i) {
    if (i === 6) { count = 0; sortCards(randOrd); }
    $(this).addClass(randDeck[count]);
    count++;
  });
}

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