gpt4 book ai didi

javascript - 第二个函数的输出错误

转载 作者:行者123 更新时间:2023-11-28 15:56:23 24 4
gpt4 key购买 nike

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

  • 在第一个函数中,硬编码值将会发生
  • 在第二个函数中,值是动态变化的。

这是我的 HTML

<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 会将传递的参数视为字符串。它们作为字符串传递,因为它们是从文本框的 value 属性中提取的,该属性是一个字符串。

这相当于这样做:

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

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

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

关于javascript - 第二个函数的输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18643692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com