2014-05-05 39 views
0

我無法通過document.getElementById從輸入字段訪問值以檢查輸入數字是偶數還是奇數。無法使用document.getElementById訪問輸入字段中的值

你能告訴我我的代碼有什麼問題嗎?

預先感謝您!

<!DOCTYPE html> 
    <html> 
     <head> 
      <title>Even or odd</title> 
      <meta charset="utf-8"/> 
      <link href="style.css" rel="stylesheet"/> 
     </head> 
     <body> 

      <form> 
       <p>Please type a number in the field and press the button to check if this is an even or an odd number.</p> 
       <input type="text" id="num" placeholder="Enter a number"/> 
       <button type="button" onclick="myFunction()">Click Me!</button>        
      </form> 


      <script> 
       var a = parseInt(document.getElementById("num").value); 
       function myFunction(){ if ((a/2)==%){ 
              alert("The number is odd"); 
             } else { 
              alert("The number is even"); 
             } 

            } 



      </script> 

     </body> 
    </html> 

回答

0

您需要移動該行以獲取函數內部的值。實際上,只有當頁面加載時才運行一次。

  function myFunction(){ 
      var a = parseInt(document.getElementById("num").value); 

另外,我不知道是什麼(a/2) == %應該意味着,但它是一個語法錯誤。

  if (a % 2 != 0) // odd test 
      if (a % 2 == 0) // even test 
相關問題