2013-06-19 116 views
1

我做了一個石頭,紙張,剪刀遊戲,並在程序中,我有一個按鈕,應該出現,但它從來沒有這樣做,它不斷給我一個錯誤,說:「未捕獲TypeError:無法讀取null屬性的'樣式'。如果我擺脫了最後的「if」聲明,它會顯示出來,但在點擊一次後會消失。按鈕不顯示後document.write

<html> 
<head> 
<title> Rock, paper, scissors game</title> 
    <script> 
    function game(){ 
     var userChoice= prompt("Do you choose rock, paper, or scissors?"); 
     document.write("You chose " + userChoice + ". <br/>") 
     var computerChoice= Math.random(); 
     if(computerChoice<=0.33){ 
      computerChoice="rock"; 
     } 
     else if(computerChoice<=0.67){ 
      computerChoice="paper"; 
     } 
     else{ 
      computerChoice="scissors"; 
     } 
     document.write("The computer chose " + computerChoice + ". <br/>"); 
     if(userChoice==computerChoice){ 
      document.write("TIE!!!!"); 
     } 
     if(userChoice=="paper" && computerChoice=="rock"){ 
      document.write('<p style="color:red">You win!</p>'); 
     } 
     if(userChoice=="rock" && computerChoice=="scissors"){ 
      document.write('<p style="color:red">You win!</p>'); 
     } 
     if(userChoice=="scissors" && computerChoice=="paper"){ 
      document.write('<p style="color:red">You win!</p>'); 
     } 
     if(userChoice=="scissors" && computerChoice=="rock"){ 
      document.write('Sorry, you lose.'); 
     } 
     if(userChoice=="rock" && computerChoice=="paper"){ 
      document.write("Sorry, you lose."); 
     } 
     if(userChoice=="paper" && computerChoice=="scissors"){ 
      document.write("Sorry, you lose."); 
     } 
     if(userChoice=="Chuck Norris"){ 
      document.write("This program bows down to your superiority, YOU WIN!!!!"); 
     } 
     if(document.getElementById("buttonclick").style.display == "none"){ 
      document.getElementById("buttonclick").style.display = "block"; 
     } 
    } 
    </script> 
</head> 
<body onload="game()"> 
    <button type="button" style="display:none;" id="buttonclick" onclick="game()">Play Again!</button> 
</body> 
</html> 
+1

沒有按鈕'buttonclick' –

+2

此外,document.write將覆蓋DOM。 – adeneo

+0

你好Arun,我剛剛解決了這個問題。我在代碼格式上犯了一個錯誤。 – vman

回答

2

document.write將覆蓋整個DOM,使按鍵你們初始化的onload實際上將您document.write的內容被覆蓋。

但是,如果您不希望自己的內容消失,建議您製作一個新的div並使用document.getElementById("div_id").innerHTML代替您的document.write()命令以保存該按鈕。

1

當您使用document.write時,它將通過覆蓋所有DOM元素來顯示其內容。

因此,您需要使用innerHtml來顯示保持您的DOM Alive的內容。