Javascript alert()函数含糊不清

时间:2015-10-14 06:53:37

标签: javascript html

我想在显示警告信息之前更改 html body 的背景颜色。这是我的代码:

var guess;
  var count=1;
  var color=["red","green","blue","yellow","indigo","purple","black","cyan","violet"];
  var num=Math.floor(Math.random()*9);
  alert("I am thinking of "+color[num]+" color");
  function do_game()
  {
    do {
      guess=get();
      if(color.indexOf(guess.toLowerCase())==-1)
      {
        alert("Sorry, I don't recognize your color");
        continue;
      }
      if(guess.toLowerCase()>color[num])
      {
        alert("Your color is alphabetically higher than my color!");
        count++;
        continue;
      }
      if(guess.toLowerCase()<color[num])
      {
        alert("Your color is alphabetically lower than my color!");
        count++;
        continue;
      }
    } while (guess.toLowerCase()!=color[num]);
    document.body.style.background=color[num];
    alert("Congratulations! You guessed the color!\n\nIt took you "+count+" guesses\n\nYou can see the color in the background");
  }

此处,只有在我关闭警报后,背景颜色才会发生变化,即使我已经在警报之前编写了更改颜色的代码。真的很困惑。 我正在使用Safari浏览器

1 个答案:

答案 0 :(得分:1)

document.body.style.background=color[num];

之前

alert("I am thinking of "+color[num]+" color");

并使用jquery。适用于我:safari,chrome,即11和firefox

$(document).ready(function() {
    var guess;
    var count=1;
    var color=["red","green","blue","yellow","indigo","purple","black","cyan","violet"];
    var num=Math.floor(Math.random()*9);
    document.body.style.background=color[num];
    alert("I am thinking of "+color[num]+" color");
    function do_game()
    {
    do {
      guess=get();
      if(color.indexOf(guess.toLowerCase())==-1)
      {
        alert("Sorry, I don't recognize your color");
        continue;
      }
      if(guess.toLowerCase()>color[num])
      {
        alert("Your color is alphabetically higher than my color!");
        count++;
        continue;
      }
      if(guess.toLowerCase()<color[num])
      {
        alert("Your color is alphabetically lower than my color!");
        count++;
        continue;
      }
    } while (guess.toLowerCase()!=color[num]);
    document.body.style.background=color[num];
    alert("Congratulations! You guessed the color!\n\nIt took you "+count+" guesses\n\nYou can see the color in the background");
    }
})