在javascript上计算提示.我的代码有什么问题

Calculate tip on javascript. What wrong with my code?

本文关键字:代码 什么 问题 我的 提示 javascript 计算      更新时间:2023-09-26

它一直显示"NaN",我不知道为什么。文本字段应显示其在"晚餐服务员多少钱?

<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>
alert没有

返回值,因此tipundefinedparseFloat(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;
}
<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>