My goal is to each div with a class of "mai开发者_如何学编程n" to have a random background color. I have the script that generates the random color but, using jquery, I only seem to be able to apply it to all divs in the class. How can I select a div, apply the color, select the next div in the class, generate a new random color, apply it and repeat? Here's my code:
$(document).ready(function() {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ')';
$('.main').css("background-color", hue);
});
$(document).ready(function() {
$('.main').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});
The code should be something like this...
$(document).ready(function() {
$('.main').each{ Function(){
$(this).css("background-color", hue); };
};
});
Bah- sorry for the mistakes. Fixed the worst of them for my own sanity's sake.. but the other answer beat me to it.
$(document).ready(function() {
$('.main').each(function(){
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' +
(Math.floor((256-199)*Math.random()) + 200) + ',' +
(Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
}
});
精彩评论