为什么这个JavaScript和HTML代码不计算结果? [英] Why this javascript and html code is not calculating the result?

查看:170
本文介绍了为什么这个JavaScript和HTML代码不计算结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

 < html> 
< body>

< script>
函数myFunction(var1,var2){
number = var1 + var2
document.write(number)
}
< / script>

< form>
编号1:< input type =textname =no1>< br>
编号2:< input type =textname =no2>< br>
< input type =buttononclick =myFunction(this.form.no1.value,this.form.no2.value)value =submit>
< / form>


< / body>
< / html>

当我为数字1插入10并为数字2插入20时,输出为:

  1020 

但我希望它显示30。
我能做什么?



**我试过myFunction(10,20),结果是30。使用 parseInt()方法简单地使用将变量值解析为整数或者使用解析方法

因为变量var1和var2返回 string 。要计算这些变量值,您需要将其转换为整数。



使用parseInt()方法

  number = parseInt(var1)+ parseInt var2)

在变量名之前使用+转换为整数,

  number = + var1 ++ var2 

尝试此代码,

 < html> 
< body>
< script>
函数myFunction(var1,var2){
number = parseInt(var1)+ parseInt(var2)
//另一种方式编号= + var1 + + var2
document.write(number )
}
< / script>
< form>
编号1:< input type =textname =no1>< br>
编号2:< input type =textname =no2>< br>
< input type =buttononclick =myFunction(this.form.no1.value,this.form.no2.value)value =submit>
< / form>

< p id =demo>< / p>

< / body>
< / html>

使用parseInt() DEMO



使用变量名前的 DEMO


This is the code:

<html>
<body>

<script>
function myFunction(var1,var2){
number=var1+var2
document.write(number)
}
</script>

<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>

<p id="demo></p

</body>
</html>

When I insert 10 for number 1 and 20 for number 2, the output is:

1020

But i want it to display 30. What can i do?

**I have tried myFunction(10,20), the result is 30.

解决方案

simply use parse the variable value to integer using parseInt() method or add "+"before to your variable name. Because variables var1 and var2 returning string. To calculate those variable values, you need to convert it as a integer.

using parseInt() method

number=parseInt(var1)+parseInt(var2)

use + before variable name to convert into integer,

number= +var1 + +var2

try this code,

<html>
    <body>
        <script>
        function myFunction(var1,var2){
            number = parseInt(var1) + parseInt(var2)
            //another way number= +var1+ +var2
            document.write(number)
        }
        </script>
    <form>
        Number 1 : <input type="text" name="no1"><br>
        Number 2 : <input type="text" name="no2"><br>
        <input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
    </form>

    <p id="demo"></p>

    </body>
</html>

using parseInt() DEMO

using + before variable name DEMO

这篇关于为什么这个JavaScript和HTML代码不计算结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆