문제

Here is my code:

var randomColor = ["red", "blue", "green", "#9CBA7F", "yellow", "#BF5FFF"];

function setRandomColor() {
 return randomColor[Math.floor(Math.random() * randomColor.length)];
}

$('.mastermind_master_cpu').each(function() {
 $(this).find('td').each(function() {
   $(this).css("background-color", setRandomColor);
 })
})

As you can see, the mastermind_master_cpu table will randomly fill with different background color. The problem is I have ten different tables and am repeating this every time. Does anyone know how I can go about making this just one function / variable and calling it when needed?

Thanks!

도움이 되었습니까?

해결책

Create a class, say random_color, to apply to each table in addition to your current class, like this:

<table class="mastermind_master_cpu random_color">...</table>

Then you can just use this once:

$('.random_color').each(function() {
 $(this).find('td').each(function() {
   $(this).css("background-color", setRandomColor);
 })
})

But as cookie monster points out, this can be done much more succinctly:

$('.random_color td').css("background-color", setRandomColor);

Demonstration

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top