How to make a document.getElementById value into an integer variable, not a string?
我想传入一个从html对象获得的值,将该值转换为整数,以便在输出之前可以对其进行算术运算。 就我的代码而言,它只是像字符串一样将它们加起来。 因此,值5 +修饰符100最终等于= 5100,而不是105。
这是我的表单代码:
1 2 3 4 5 6 7 8 9 | <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> |
这是我的脚本:
1 2 3 4 5 6 7 8 | function addTweet() { var mod = 100; var results = document.getElementById("addTweets").value; results += mod; document.getElementById("tweetsOutput").innerHTML = results; } |
一元加号(
1 2 3 4 | var results = +document.getElementById("addTweets").value; ... typeof( results ); // number |
使用parseInt:
1 2 | var results = document.getElementById("addTweets").value; var intResults = parseInt(results, 10) + mod; |
您可以使用
1 | var results = parseInt(document.getElementById("addTweets").value); |
只需添加parseInt,即可正常添加
1 | var results = parseInt(document.getElementById("addTweets").value); |
编辑:
parseInt替代,您可以使用" | 0"使用按位或零
1 | var results = document.getElementById("addTweets").value|0; |
通常,可以通过对字符串数值进行数学运算将其转换为整数:
1 2 3 4 5 | x ="9"; //String numerical value y = 10;//integer value alert(x+y)// output 910; x = x*1; alert(x+y) // output 19 |
查看此演示
尝试:
1 2 3 4 5 | 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 |