简体   繁体   English

javascript document.getElementById()。value

[英]javascript document.getElementById().value

Sorry, I'm newbie, 对不起,我是新手,

<html>
<head>
<script type="text/javascript">
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var z = x + y;
alert(z);
</script>
</head>

<body>
<input type="number" id="x" />
<input type="number" id="y" />
</body>

</html>

If my input x = 100, and y input = 200. My popup alert are 100200. 如果我的输入x = 100,y输入= 200.我的弹出警报是100200。

How to fixed this? 怎么解决这个?

thank you. 谢谢。

It's because the value is a string , you need to convert it to a number and then do the addition.. This should do it.. 这是因为该值是一个string ,您需要将其转换为数字,然后进行添加..这应该这样做..

<html>
<head>
<script type="text/javascript">
    var x = parseInt(document.getElementById('x').value);
    var y = parseInt(document.getElementById('y').value);
    var z = x + y;
    alert(z);
</script>
</head>

<body>
    <input type="number" id="x" />
    <input type="number" id="y" />
</body>

</html>

Function parseInt will convert the string to an integer number and then 100+200 will be 300. 函数parseInt会将字符串转换为整数,然后100 + 200将为300。

Find the Fiddle here 这里找到小提琴

Use 采用

var z = parseInt(x) + parseInt(y); var z = parseInt(x)+ parseInt(y);

You need to typecast variables using parseInt(var) since they are strings. 您需要使用parseInt(var)对变量进行类型转换,因为它们是字符串。

<html>

<head>
    <script type="text/javascript">
    var x = document.getElementById('x').value;
    var y = document.getElementById('y').value;
    var z = parseInt(x) + pasreInt(y);
    alert(z);
    </script>
</head>

<body>
    <input type="number" id="x" />
    <input type="number" id="y" />
</body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM