简体   繁体   English

无法使用document.getElementById访问输入字段中的值

[英]Cannot access value in input field with document.getElementById

I cannot access a value from an input field with document.getElementById to check if the input number is even or odd. 我无法使用document.getElementById从输入字段访问值来检查输入数字是偶数还是奇数。

Could you please tell me what is wrong with my code? 您能告诉我我的代码有什么问题吗?

Thank you in advance! 先感谢您!

<!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>

You need to move that line of code that fetches the value inside the function. 您需要移动该行代码以获取函数内部的值。 As it is, that only runs once, when the page loads. 实际上,页面加载时仅运行一次。

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

Also, I don't know what (a/2) == % is supposed to mean, but it's a syntax error. 另外,我不知道(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