簡體   English   中英

表單輸入,需要幫助設置輸入值

[英]Form input, need help setting value of input

我正在嘗試獲取輸入字段的值,因此根據輸入值是 0 還是 1,輸入的值是一或二,它應該顯示在控制台中。

<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>demo</title>
    <meta charset="utf-8">
    <style>

    </style>
</head>

<body>
    <p>Input 0 or 1.</p>
    <input id="ok" type="text">
    <button onclick="functionn()"></button>
    <script>
          var x = document.getElementById("ok").value;

        function functionn() {
            if (x == 0) {
                ok = "one";
                console.log(ok); }
             else if (x == 1) {
                ok = "two";
                console.log(ok);

            } else {
                alert("please input 0 or 1");
            }
        }

    </script>

</body>

</html

你離得那么近!

您遇到的問題是“x”變量,它保存頁面加載后輸入的值,即空字符串。

您需要將該變量放入函數中,因此每次單擊按鈕時,您都會“轉到”並檢查輸入的值,然后將其存儲在“x”變量中。

希望這有幫助! =]

嘗試一下:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>demo</title>
        <meta charset="utf-8" />
        <style></style>
    </head>

    <body>
        <p>Input 0 or 1.</p>
        <input id="ok" type="text" />
        <button onclick="functionn()"></button>
        <script>
            var x = document.getElementById("ok");

            function functionn() {
                if (x.value === "0") {
                    ok = "one";
                    console.log(ok);
                } else if (x.value === "1") {
                    ok = "two";
                    console.log(ok);
                } else {
                    alert("please input 0 or 1");
                }
            }
        </script>
    </body>
</html>

暫無
暫無

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

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