简体   繁体   English

JQuery .val无法正常工作

[英]JQuery .val not working

I've checked a number of related questions/answers on SO but can't find a solution. 我在SO上检查了一些相关的问题/答案,但找不到解决方案。 I have the following code: 我有以下代码:

    <html>
    <head>
    <title>Admin</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="#">

    <script src="jquery-3.3.1.js"> </script>
    </head>
    <body>
    <div>Test area</div>
    <br/>

    <script>
        document.write('<button onclick="updateFunc()">TEST</button>');
        document.write('<input type="text" id="mytext">');

        function updateFunc()
        {
            document.write($('mytext').val());
        }
    </script>
    </body>
    </html>

The output When I click the TEST button is: 输出当我单击TEST按钮时:

    undefined

Don't know what I'm doing wrong here. 不知道我在这里做错了什么。 I've tried moving things around, eg order of javascript, taken the HTML out into the HTML body rather than "printing" it in the JS, but still I keep getting undefined. 我已经尝试过移动的东西,例如javascript的顺序,将HTML带入HTML主体,而不是在JS中“打印”它,但我仍然不断定义。 I inspected the element and I get: 我检查了元素,得到了:

    <input type="text" id="mytext">

in the browser. 在浏览器中。

Change to $('#mytext').val() since it is ID ( # ) selector. 更改为$('#mytext').val()因为它是ID( # )选择器。

<script>
    document.write('<button onclick="updateFunc()">TEST</button>');
    document.write('<input type="text" id="mytext">');

    function updateFunc()
    {
        document.write($('#mytext').val());
    }
</script>

You forgot the "#" in your jQuery selector. 你忘记了jQuery选择器中的“#”。

function updateFunc()
{
   document.write($('#mytext').val());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM