我有一个简单的html和JS脚本,但是当我在输入数字字段中输入2时,它不会触发警报消息onchange。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("partysize");
if (x==2) window.alert ("You entered" + x);
}
</script>
</head>
<body bgcolor="#6BD3FF" text="#000000" link="#0000EE" vlink="#551A8B" alink="#FF0000">
<div align="center">
<br> Please enter the party size:
<input type="number" id = "partysize" name="partySize" onchange="myFunction()" >
<br />
<input type="SUBMIT" name="submitButton">
</form>
<br />
</div>
</body>
</html>
答案 0 :(得分:1)
呃,通过获取元素的值来修复:
function myFunction() {
var x = document.getElementById("partysize").value;
if (x==2) window.alert ("You entered" + x);
}
答案 1 :(得分:0)
您需要从输入框中获取值,但在您的代码段x
中是唯一的dom元素。使用this.value
将值传递给更改处理程序。此外,parseInt
会将字符串中的数字值转换为数字
function myFunction(x) {
if (parseInt(x, 10) === 2) {
alert("You entered" + x);
}
}
&#13;
<body bgcolor="#6BD3FF" text="#000000" link="#0000EE" vlink="#551A8B" alink="#FF0000">
<div align="center">
<br> Please enter the party size:
<input type="number" id="partysize" name="partySize" onchange="myFunction(this.value)">
<br/>
<input type="submit" name="submitButton">
<br />
</div>
</body>
&#13;