我有这段代码。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input onclick="result.value = m1*m2; m1.value = (+m1.value -1);" type="button" id="minus1" value="minus" />
<input onclick="result.value = m1*m2; m1.value = (+m1.value +1);" type="button" id="plus1" value="plus" />
<input type="textbox" id="m1" value="1" />
<br />
<input onclick="result.value = m1*m2; m2.value = (+m2.value -1);" type="button" id="minus2" value="minus" />
<input onclick="result.value = m1*m2; m2.value = (+m2.value +1);" type="button" id="plus2" value="plus" />
<input type="textbox" id="m2" value="1" />
<br />
<br />
Result :<input type="textbox" id="result" />
</body>
</html>
为什么每次更改任何+或 - 按钮时都会获得NaN值???
答案 0 :(得分:5)
您正在乘以m1*m2
。您应该使用:m1.value*m2.value
。
在某些浏览器中,m1
会返回标识为m1
的元素。但是,您想要乘以的只是值m1.value
。
编辑HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input onclick="result.value = m1.value*m2.value; m1.value = (+m1.value -1);" type="button" id="minus1" value="minus" />
<input onclick="result.value = m1.value*m2.value; m1.value = (+m1.value +1);" type="button" id="plus1" value="plus" />
<input type="textbox" id="m1" value="1" />
<br />
<input onclick="result.value = m1.value*m2.value; m2.value = (+m2.value -1);" type="button" id="minus2" value="minus" />
<input onclick="result.value = m1.value*m2.value; m2.value = (+m2.value +1);" type="button" id="plus2" value="plus" />
<input type="textbox" id="m2" value="1" />
<br />
<br />Result :
<input type="textbox" id="result" />
</body>
</html>
如果我建议,您应该在onclick
事件中使用一个函数。事情将更清晰,更易于维护,您可以添加更多支票,就像输入中的数字有效一样。请参阅下面的示例。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function update(inputToChange, changeValue) {
var parsedValue = parseFloat(inputToChange.value);
if (isNaN(parsedValue)) {
alert(inputToChange.value+' is not a a valid number.');
}
else {
result.value = m1.value * m2.value;
inputToChange.value = parsedValue + changeValue;
}
}
</script>
</head>
<body>
<input onclick="update(m1, -1)" type="button" id="minus1" value="minus" />
<input onclick="update(m1, 1)" type="button" id="plus1" value="plus" />
<input type="textbox" id="m1" value="1" />
<br />
<input onclick="update(m2, -1)" type="button" id="minus2" value="minus" />
<input onclick="update(m2, 1)" type="button" id="plus2" value="plus" />
<input type="textbox" id="m2" value="1" />
<br />
<br />Result :
<input type="textbox" id="result" />
</body>
</html>
答案 1 :(得分:1)
您使用的m1*m2
是文本框的ID而不是其值。
使用:result.value = m1.value*m2.value
保证result.value = m1*m2;