Javascript 如何将 document.getElementById 值变成整数变量,而不是字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13693580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a document.getElementById value into an integer variable, not a string?
提问by Hales_W
I want to pass in a value, obtained from the an html object, convert that value into an integer so I can run arithmetic on it before outputting it. As my code stands now, it just adds them up like a string. So a value of 5 + a modifier of 100 ends up equaling = 5100, not 105.
我想传入一个从 html 对象获得的值,将该值转换为整数,以便我可以在输出之前对其进行算术运算。就我现在的代码而言,它只是将它们像字符串一样加起来。因此,值 5 + 修饰符 100 最终等于 = 5100,而不是 105。
Here's my form code:
这是我的表单代码:
<form>
Add Amount: <select id="addTweets">
<option value=5>5</option>
<option value=10>10</option>
<option value=15>15</option>
</select>
</br>
<input type="button" value="Add It" onclick="addTweet()" />
</form>
Here's my script:
这是我的脚本:
function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;
document.getElementById("tweetsOutput").innerHTML = results;
}
回答by 0x499602D2
The unary plus (+) coerces its operand into a number:
一元加号 ( +) 将其操作数强制转换为数字:
var results = +document.getElementById("addTweets").value;
...
typeof( results ); // number
回答by The Alpha
You can use parseInt
您可以使用 parseInt
var results = parseInt(document.getElementById("addTweets").value);
回答by davidethell
Use parseInt:
使用 parseInt:
var results = document.getElementById("addTweets").value;
var intResults = parseInt(results, 10) + mod;
回答by Kokizzu
just add parseInt, then you could add it normally
只需添加parseInt,然后您就可以正常添加它
var results = parseInt(document.getElementById("addTweets").value);
EDIT:
编辑:
parseInt alternate, you can use "|0" use bitwise-or zero
parseInt 替代,您可以使用“|0”使用按位或零
var results = document.getElementById("addTweets").value|0;
回答by ngunha02
Try:
尝试:
var valResult = document.getElementById("addTweets").value; // get the value of the field
var results = parseInt(valResult) + mod; // convert the value to int to do calculation
document.getElementById("addTweets").value = results; // assign results to the field value

