继续展示" NaN"而且我不知道为什么。文本字段应显示其输入的"晚餐服务员多少钱的10%和20%?"
<body>
<script type="text/javascript">
function tipp()
{
var tip = alert("You Calculated The tip " + document.form1.textfield.value + " in the Textfield.");
tip = parseFloat(tip);
var tf2 = tip * .10;
var tf3 = tip * .20;
document.form1.textfield2.value = tf2;
document.form1.textfield3.value = tf3;
}
</script>
<form name="form1">
How much was dinner,waiter?<input type="text" name="textfield" id="tip"><br><br>
<input type="button" onClick = "tipp()" value="Calculate Tip"><br><br>
10% <input type="text" id="textfield2"><br><br>
20%<input type="text3" id="textfield3"><br><br>
</form>
</body>
答案 0 :(得分:2)
alert
没有返回值,因此tip
将为undefined
。 parseFloat(undefined)
是NaN
。 NaN
的所有数学计算都会产生NaN
。
不是使用alert
的返回值,而是从您的字段中获取值:
var tip = parseFloat(document.getElementById("tip").value);
示例(我删除了警告,我不知道您要在那里展示什么;另外,我在所有字段中使用了getElementById
):
function tipp() {
var tip = parseFloat(document.getElementById("tip").value);
var tf2 = tip * .10;
var tf3 = tip * .20;
document.getElementById("textfield2").value = tf2;
document.getElementById("textfield3").value = tf3;
}
&#13;
<form name="form1">
How much was dinner,waiter?
<input type="text" name="textfield" id="tip">
<br>
<br>
<input type="button" onClick="tipp()" value="Calculate Tip">
<br>
<br>10%
<input type="text" id="textfield2">
<br>
<br>20%
<input type="text3" id="textfield3">
<br>
<br>
</form>
&#13;