javascript - JQuery .val 不工作

标签 javascript jquery html

我已经检查了一些关于 SO 的相关问题/答案,但找不到解决方案。我有以下代码:

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

当我点击 TEST 按钮时的输出是:

    undefined

不知道我在这里做错了什么。我试过四处移动东西,例如javascript 的顺序,将 HTML 取出到 HTML 主体中而不是在 JS 中“打印”它,但我仍然没有定义。我检查了元素并得到:

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

在浏览器中。

最佳答案

更改为 $('#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>

关于javascript - JQuery .val 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49702089/

相关文章:

javascript - 如何在动态添加的数组中具有不同的值

javascript - 如何在javascript中输出调用对象?

javascript - jQuery 模糊功能不起作用

javascript - 在 Javascript 和 HTML 中显示图像

html - CSS 在 2 行后中断(使用相同的类)

javascript - 单击按钮时自动更新表格

javascript - map.fitBounds 之后有回调吗?

javascript - 使用 projekktor/jquery/javascript 停止加载/缓冲视频

javascript - 在显示隐藏元素时,由于滚动,它显示在错误的位置,仅在 chrome 中

jquery - 元素中 .addClass() 方法的问题