2015-10-14 4 views
1

Я хочу изменить цвет фона html body перед отображением предупреждающего сообщения. Это мой код:Javascript alert() function ambiguity

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 браузер

+2

Попробуйте нулевую миллисекунду setTimeout. –

+0

Можете ли вы добавить jsfiddle с вашей проблемой? Я попытался воспроизвести вашу проблему, но, похоже, она работала на моем конце. –

+0

Я использую сафари. Я проверю другой браузер –

ответ

1

Помещенный

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

перед тем

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

и использование JQuery. Работает для меня: сафари, хром, то есть 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"); 
    } 
})