Randomized Grouping Jquery
I decided that my previous question wasnt perhaps clear in both title and result, so I decided to ask the question like this...
I have 3 categories (A,B,C) and in these categories i have 3 items each. So category A)dog,cat,mouse B)apple,cherry,banana C)red,green,yellow.
I was wondering if its possible to group these items from th开发者_运维知识库e categories at random. So for example each time you click on the same button it would group: dog,apple,yellow or cat,cherry,green or mouse,apple,red , etc... and adds the class .grouped or whatever to that group. with only one possible group at a time with three items.
so i guess it would be like from start
class="dog"
class="cat"
class="mouse"
class="apple"
class="cherry"
class="banana"
class="red"
class="green"
class="yellow"
and then you click button & get:
class="dog grouped"
class="apple grouped"
class="yellow grouped"
click button again & get
class="cat grouped"
class="cherry grouped"
class="green grouped"
any thoughts or suggestions greatly appreciated
-david
This will probably get you going. For the html:
<span class="animal">dog</span>
<span class="animal">cat</span>
<span class="animal">mouse</span>
<span class="fruit">apple</span>
<span class="fruit">cherry</span>
<span class="fruit">banana</span>
<span class="colour">red</span>
<span class="colour">green</span>
<span class="colour">yellow</span>
Then this javascript will randomly add the class
function regroup() {
//remove existing
$(".grouped").removeClass("grouped");
//the random Math.floor is just to generate a random number
$(".animal:eq(" + (Math.floor(Math.random() * 4)) + ")").addClass("grouped");
$(".fruit:eq(" + (Math.floor(Math.random() * 4)) + ")").addClass("grouped");
$(".colour:eq(" + (Math.floor(Math.random() * 4)) + ")").addClass("grouped");
}
The idea is to generate a random number within the number of each class, and then add the class to it.
Its possible as you can see below. There are definitely more elegant ways to do this, but I figured this would be pretty straight forward to understand.
http://jsfiddle.net/EN7HQ/1/
JS
var groupA = ["dog","cat","mouse"],
groupB = ["apple", "cherry","bannana"],
groupC = ["red","green","yellow"];
$("#clickme").click(function(){
$("#groups").children().remove();
var itemA = groupA[Math.round(Math.random()*2)],
itemB = groupB[Math.round(Math.random()*2)],
itemC = groupC[Math.round(Math.random()*2)];
$("#groups").append("<div class='" + itemA + " grouped'>" + itemA + "</div>");
$("#groups").append("<div class='" + itemB + " grouped'>" + itemB + "</div>");
$("#groups").append("<div class='" + itemC + " grouped'>" + itemC + "</div>");
});
Markup
<div id="clickme">Click Me</div>
<div id="groups">
</div>
精彩评论