向使用jQuery复制的数组中的元素添加随机类 [英] Adding a random class to element from an array that duplicates using jQuery

查看:161
本文介绍了向使用jQuery复制的数组中的元素添加随机类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个匹配的游戏,并且试图从数组中添加一个要匹配的类. 我下面的代码创建所需的类,然后将它们随机化.

我的问题是在randomizeDeck函数中.我试图两次将每个类添加到指定的元素两次.当我console.log代码时,这些类将添加到前六个元素中,而不是最后六个元素中,而我需要这样做,以便我可以在要创建的匹配游戏中对这些类进行匹配.

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();

我建议使用一个单独的变量来跟踪索引,而不是each索引.一旦您遍历了所有内容,最好重新洗牌,这样第二遍的顺序就不同了. 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++;
  });
}

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 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++;
  });
}

这篇关于向使用jQuery复制的数组中的元素添加随机类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆