2017-04-22 57 views
-1

我還在使用JavaScript。我試圖製作一個包含2個按鈕的程序,一旦點擊一個按鈕,它會創建一個隨機數。程序沒有運行

問題是,當我試圖比較它們時,它沒有顯示哪一個更大。首先,我認爲問題是變量不是全局的,但它沒有改變任何東西。

有人可以幫我找到問題嗎?

這裏是的JavaScript代碼

var par1 = document.getElementById("para1"); 
 
var par2 = document.getElementById("para2"); 
 
var winner = document.getElementById("win"); 
 
    
 
function button1() { 
 
    num1 = Math.floor(Math.random() * 7); 
 
    par1.innerHTML = num1; 
 
} 
 
    
 
function button2() { 
 
    num2 = Math.floor(Math.random() * 7); 
 
    par2.innerHTML = num2; 
 
} 
 
if (num1 > num2) { 
 
    winner.innerHTML = "the winner is player 1"; 
 
} else { 
 
    winner.innerHTML = "the winner is player 2"; 
 
}
<!DOCTYPE html> 
 
<html> 
 
    
 
<head> 
 
    <meta charset="utf-8"> 
 
    <title>dicestimulator</title> 
 
    <link rel="stylesheet" href="dicestimulator.css"> 
 
</head> 
 
    
 
<body> 
 
    <div class="container"> 
 
     <div> 
 
      <h1>Player1</h1> 
 
      <button type="button" name="button1" onclick="button1()" id="but1">roll 
 
    dice</button> 
 
      <p id="para1">Click the button to see what you get</p> 
 
     </div> 
 
     <div> 
 
      <h1>Player2</h1> 
 
      <button type="button" name="button2" id="but2" onclick="button2()">roll 
 
    dice</button> 
 
      <p id="para2">Click the button to see what you get</p> 
 
     </div> 
 
     <p id="win">let's see who wins!!!</p> 
 
     <script src="dicestimulator.js"></script> 
 
    </div> 
 
</body> 
 
    
 
</html>

回答

1
if(num1>num2){ 
winner.innerHTML="the winner is player 1"; 
}else{ 
winner.innerHTML="the winner is player 2"; 
} 

您不在HTML代碼中調用上述塊號。

我對你的解決方案做出第三個按鈕調用該函數getwinner

function getWinner() { 
if(par1.val>par2.val){ 
winner.innerHTML="the winner is player 1"; 
} else{ 
winner.innerHTML="the winner is player 2"; 
} 
} 

請注意,你不能調用這些功能以外的功能創建的本地變量。在創建它們的函數的作用域之後,num1和num2不再存在。

1

的一段代碼:

if(num1>num2){ 
winner.innerHTML="the winner is player 1"; 
}else{ 
winner.innerHTML="the winner is player 2"; 
} 

...是不在函數內

它在腳本初始加載時運行。

稍後,您將調用button1button2函數。這些改變了num1的值。

您再也不會比較的值

如果要在運行button1button2函數時比較它們,那麼需要在這些函數處於調用狀態時調用代碼。