繁体   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