添加函数在 JavaScript 中不起作用

当我使用该函数将两个数字相加时,它看起来像 (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>


潇潇雨雨
浏览 88回答 3
3回答

Cats萌萌

您正在添加字符串“2”加“2”,因此它们只是附加的。您需要先输入一个数字。console.log(parseInt("2")+Number("2"))

RISEBY

该value属性返回一个字符串,为其+定义了用于连接的运算符。您可以使用一元加运算符将它们简单地转换为数字。function adding(a, b) {&nbsp; return (a + b);}document.getElementById("press").onclick = function() {&nbsp; var first = +document.getElementById("one").value;&nbsp; var second = +document.getElementById("two").value;&nbsp; alert(adding(first, second));}<input type="number" id="one"><input type="number" id="two"><button id="press">seed</button>

拉丁的传说

您只能在返回的地方编写 parseint。&nbsp;function adding (a, b){&nbsp; &nbsp; return (parseInt(a) + parseInt(b));}document.getElementById("press").onclick = function(){&nbsp; &nbsp; var first = document.getElementById("one").value;&nbsp; &nbsp; var second = document.getElementById("two").value;&nbsp; &nbsp; alert(adding(first, second));}<input type="number" id="one"><input type="number" id="two"><button id="press">seed</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript