2015-06-26 31 views
0

我有一個輸入框並提交按鈕作爲html,我想輸入任何數字在輸入框中,然後警報消息將顯示,如果它是偶數或奇數。如果它甚至比段落的其中一個文字顏色將變成紅色其他藍色。這裏是我的代碼:Javascript事件和css

<!doctype html> 
    <html lang="en"> 
    <head> 
    <script src="jsfile.js"></script> 
    </head> 

    <body> 
    <input type="text" id="inputBox"/> 
    <button type="button" onclick="AlertBox()">Submit</button> 

    <p id="p12">My first paragraph</p> 
    </body> 

    </html> 

外部js文件:

function AlertBox() 
    { 
     var number=document.getElementById("inputBox").value; 
     if (number/2 == 0) 
     { 
      alert(number + " is even and ok to go."); 
      document.getElementById("p12").style.color = "red"; 

     } else 
     { 
      alert(number + " is not even and not ok to go."); 
      document.getElementById("p12").style.color = "blue"; 
     } 
    } 
+0

嘗試變種數= parseInt函數(的document.getElementById( 「輸入框」)值。); 另外,number/2 == 0不會讓你得到你想要的,嘗試模運算符: if(number%2 == 0){...} – neilsimp1

+0

記住選擇你的答案。 – connexo

回答

2

function AlertBox() { 
 
    var number = document.getElementById("inputBox").value; 
 
    if (number % 2 == 0) { 
 
    alert(number + " is even and ok to go."); 
 
    document.getElementById("p12").style.color = "red"; 
 

 
    } else { 
 
    alert(number + " is not even and not ok to go."); 
 
    document.getElementById("p12").style.color = "blue"; 
 
    } 
 
}
<!doctype html> 
 
<html lang="en"> 
 

 
<head> 
 
    <script src="jsfile.js"></script> 
 
</head> 
 

 
<body> 
 
    <input type="text" id="inputBox" /> 
 
    <button type="button" onclick="AlertBox()">Submit</button> 
 

 
    <p id="p12">My first paragraph</p> 
 
</body> 
 

 
</html>

+0

Perfect Connexo,謝謝 – anam

2

您不能測試一些甚至number/2 == 0之中。您需要使用modulo operatornumber % 2 == 0