我在父div中有一个子div的集合,子div是动态生成的,并且都具有相同的类名.
我的问题是如何使用下面的jquery示例代码为每个子div应用不同的背景颜色
<div id="someid">
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)
在这里,我想为每个子div应用不同的背景颜色(class ="bars")
提前致谢.
像这样的东西:
var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];
$('#someid .bar').each(function(i) {
$(this).css('background-color', '#'+colors[i % colors.length]);
});
Run Code Online (Sandbox Code Playgroud)
要生成随机颜色,您可以使用:
function randomColor() {
return 'rgb('+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+')'
}
$('#someid .bar').each(function(i) {
$(this).css('background-color', randomColor());
});
Run Code Online (Sandbox Code Playgroud)
演示: