我已经检查了一些关于 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/