为了账号安全,请及时绑定邮箱和手机立即绑定

添加函数在 JavaScript 中不起作用

添加函数在 JavaScript 中不起作用

潇潇雨雨 2023-01-06 15:13:48
当我使用该函数将两个数字相加时,它看起来像 (2+2=22) 一样彼此相邻,尽管它与其他数学运算符(* 和 /)配合得很好    <html>  <head>            <title>Adding</title>          </head>  <body>            <input type="number" id="one">      <input type="number" id="two">      <button id="press">seed</button>        <script type="text/javascript">                function adding (a, b){                return (a + b);                }        document.getElementById("press").onclick = function(){            var first = document.getElementById("one").value;            var second = document.getElementById("two").value;                            alert(adding(first, second));        }            </script>      </body>
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

您正在添加字符串“2”加“2”,因此它们只是附加的。您需要先输入一个数字。

console.log(parseInt("2")+Number("2"))


查看完整回答
反对 回复 2023-01-06
?
RISEBY

TA贡献1856条经验 获得超5个赞

该value属性返回一个字符串,为其+定义了用于连接的运算符。您可以使用一元加运算符将它们简单地转换为数字。


function adding(a, b) {

  return (a + b);

}

document.getElementById("press").onclick = function() {

  var first = +document.getElementById("one").value;

  var second = +document.getElementById("two").value;


  alert(adding(first, second));

}

<input type="number" id="one">

<input type="number" id="two">

<button id="press">seed</button>


查看完整回答
反对 回复 2023-01-06
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

您只能在返回的地方编写 parseint。


 function adding (a, b){

    return (parseInt(a) + parseInt(b));

}

document.getElementById("press").onclick = function(){

    var first = document.getElementById("one").value;

    var second = document.getElementById("two").value;


    alert(adding(first, second));

}

<input type="number" id="one">

<input type="number" id="two">

<button id="press">seed</button>


查看完整回答
反对 回复 2023-01-06
  • 3 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信