0

I have a long set of divs where I'd like to change all of their background colors to a random color when someone clicks the "home" button with a cascading delay (which I'll add later). I've been testing this in jfiddle and I can't seem to get it to work.

For example, with a while loop of 1-10 on jsfiddle: http://jsfiddle.net/PWvaw/17/

Am I having a var scope issue or is there an issue with placing a string/variable combo in a getElementByID method? It seems to show, when I place head tags in the HTML section of jfiddle, the code turns red right after the "getElementById("

switch (randomNumberOne) {
  case 1:
    document.getElementById(

Any help would be appreciated. I did a search here already and found nothing conclusive, however, I apologize if I missed an answer. Thanks!

4

1 回答 1

2

只需删除颜色代码中的分号即可。

function backgroundColorChange() {
    var num = 1;
    while (num <= 10) {
        var randomNumberMe = Math.floor((Math.random()*10)+1);
        console.log(randomNumberMe);
        switch (randomNumberMe) {
            case 1:
              document.getElementById('r' + num).style.backgroundColor = '#db0058';
              break;
            case 2:
              document.getElementById('r' + num).style.backgroundColor = '#80e800';
              break;
            case 3:
              document.getElementById('r' + num).style.backgroundColor = '#ffb700';
              break;
            case 4:
              document.getElementById('r' + num).style.backgroundColor = '#4b5ed7';
              break;
            default:
              document.getElementById('r' + num).style.backgroundColor = '#ffffff';
              break;
        }
        num += 1;
    }
}

jsfiddle

于 2012-07-11T21:47:29.457 回答