我正在使用以下代码:
<script type="text/javascript">
function minus(){
var t=document.getElementById("totalcost").value;
var u=document.getElementById("advpay").value;
var set=(t-u);
document.getElementById("textfield").value=set;
return true;
}
</script>
我在 totalcost id 字段 中输入了 “6000” 作为值,在 advpay id 字段 中输入了 “1000” .所以在 textfield id 字段中,它应该显示 5000 (6000-1000),但它给出的答案是 NaN 。错误在哪里?
最佳答案
<script type="text/javascript">
function minus() {
var t = parseInt(document.getElementById("totalcost").value, 10),
u = parseInt(document.getElementById("advpay").value, 10),
set = (t - u);
document.getElementById("textfield").value = set;
return true;
}
</script>
发生这种情况是因为您正试图减去两个字符串! value
返回输入的字符串,您需要将其解析为数字才能减去它们。请记住指定 parseInt
的基数,否则数字可能无法解析为小数。参见 this answer获取更多详细信息。
关于Javascript 给出 NaN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177519/