对指定的每个元素应用随机类 [英] Apply a random class to every element specified
问题描述
我试图添加一个随机类, li>元素在我的#container div
I am trying to add a random class to even < li > element within my #container div
这是我的代码:
$( "#container li" ).each(
$().ready(function() {
$("#container li:random").addClass("one");
$("#container li:random").addClass("two");
$("#container li:random").addClass("three");
})
);
问题是我有十个< li>元素,我想让每个元素以随机方式接收三个可能的类之一。
The problem is that I have ten < li > elements and I want each of these elements to receive one of the three possible classes in a random fashion.
但是,我上面的代码只分配了三个< li>元素与类别, li> elements class-less。
However my code above only assignes three < li > elements with the classes leaving the remaining seven < li > elements class-less.
我尝试了其他代码片段,但没有一个随机地将一个类列表应用到指定的所有元素。
I have tried other snippets of code but none of which randomly apply a list of classes to ALL elements specified.
我已尝试过此帖子的片段这里,但没有一个产生所需的结果,确保所有的元素都得到一个随机类。
I have tried snippets from this post HERE but none of which produce the desired result of making sure all elements get a random class.
谢谢你帮助。
推荐答案
您可以使用一个类数组,然后将一个随机类从该数组分配到匹配一个选择器的元素
You can use an array of classes and then assign a random class from that array to each element matching a selector like this:
$(document).ready(function(){
var classes = ["one", "two", "three"];
$("#container li").each(function(){
$(this).addClass(classes[~~(Math.random()*classes.length)]);
});
});
这篇关于对指定的每个元素应用随机类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!