簡體   English   中英

無法使用document.getElementById訪問輸入字段中的值

[英]Cannot access value in input field with 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>

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

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

另外,我不知道(a/2) == %是什么意思,但這是語法錯誤。

            if (a % 2 != 0) // odd test
            if (a % 2 == 0) // even test 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM