JavaScript中无法识别HTML值



在我的J.S代码中无法识别我的html输入数值,它会提醒Nothing。。如果我想制作另一个代码,也会发生同样的事情

var age = document.getElementById("ent").value;
document.getElementById("press").onclick = function() {
alert(age);
}
<input type="number" id="ent">
<button id="press">seed</button>

您在首次加载页面时设置age,而不是在用户填写输入之后。在单击处理程序中分配变量。

document.getElementById("press").onclick = function() {
var age = document.getElementById("ent").value;
alert(age);
}
<input type="number" id="ent">
<button id="press">seed</button>

<html> <head> <title>Quick Coding</title> </head> <body> <input type="number" id="ent"> <button id="press">seed</button> <script type="text/javascript">  document.getElementById("press").onclick = function(){ var age = document.getElementById("ent").value; alert(age); } </script> </body> </html>

请根据我在这里给出的内容修改您的代码。在你的代码中,年龄值只是在页面开始时收集值,但你需要在放入数据后获得值

或者,只要用户输入任何内容,就反映变量中输入字段的任何更改:

<input type="number" id="ent" oninput="window.age = this.value" >
<button id="press" onclick="alert(window.age)">seed</button>

首先,您还没有用值初始化输入。。。

<input type="number" value="80" id="ent">

第二,你可以删除所有JS,直接在按钮中内联。。。

<button id="press" onclick="alert(ent.value);">seed</button>

最新更新