【发布时间】:2022-12-06 04:39:17
【问题描述】:
我正在尝试编写一个简单的 JavaScript 函数,它应该执行以下操作:
- 用户在 HTML 输入字段中输入数字
- 单击提交按钮时,JavaScript 函数会提醒用户在屏幕上输入。
由于某种原因,代码没有运行。
function calcGuess() {
var value = document.getElementById('userValue').value;
alert(value);
}
document.getElementById("subButton").onclick = calcGuess();
<div class='wrapper'>
<form id='userInput'>
<label id='numLabel' for='userValue'>Enter a Number:</label>
<input id='userValue' type='number'></input>
<button id='subButton' type='button'>Enter</button>
</form>
</div>
【问题讨论】:
-
对于您的 onclick,传递不带 () 的函数名称。
-
如果单击“运行代码 sn-p”,您会看到警报在页面加载后立即发生。这是由于在
calcGuess之后使用了括号。
标签: javascript html variables error-handling