在第二个函数上获得错误的输出

getting wrong output on the second function

本文关键字:错误 输出 第二个 函数      更新时间:2023-09-26

我有一个代码,其中我有两个函数:

  • 在第一个函数中,硬编码值将消失
  • 在第二个函数中,值是动态的。

这是我的网页

<input type="text" name="txt1" id="txt1">
<input type="text" name="txt2" id="txt2">
<input type="text" name="txt3" id="txt3">
<input type="submit" value= "ADD Value" onclick="Addhardcode(1,2,3)">
<input type="submit" value="Add" onclick ="Add()">

脚本:

<script type="text/javascript">
<!--
function Addhardcode(a,b,c)
{
    a+b+c;
    alert(a+b+c);
}
function Add()
{
    var x= document.getElementById("txt1")
    var y= document.getElementById("txt2")
    var z= document.getElementById("txt3")
    var a=x.value;
    var b=y.value;
    var c=z.value;
    Addhardcode(a,b,c);
}
//-->
</script>

单击按钮ADD Value时,我得到了正确的答案,但是,单击按钮Add我没有得到正确的答案。 如果我在文本框中传递 4 、5 和 6,则输出为 456 而不是 15。我做错了什么。 如果我必须在文本框上进行验证,它只需要数字,或者它不能为空.那我能为此做些什么

你得到串联答案的原因是因为JavaScript会将传递的参数视为字符串。它们作为字符串传递,因为它们是从文本框的值属性(字符串)中提取的。

这相当于这样做:

alert('4'+'5'+'6'); // Gives '456'

要实际添加数字,您需要先将它们转换为整数。

var a = parseInt(x.value);
var b = parseInt(y.value);
var c = parseInt(z.value);

当您当前调用x.value时,它将以字符串形式返回,因此+ operator将仅连接值。

使用 parseInt() 将值解析为整数。

 var a = parseInt(x.value);
 var b = parseInt(y.value);
 var c = parseInt(z.value);
在你的

代码中a,b,c被认为是字符串,所以+只是附加它们。

您必须将它们转换为整数,例如

       var a= parseInt(x.value,10);
       var b= parseInt(y.value,10);
       var c= parseInt(z.value,10);

在传递到功能Addhardcode之前