如何将document.getElementById值转换为整数变量,而不是字符串? [英] How to make a document.getElementById value into an integer variable, not a string?

查看:92
本文介绍了如何将document.getElementById值转换为整数变量,而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传入一个从html对象获取的值,将该值转换为整数,以便在输出之前对其进行算术运算。正如我的代码现在所说,它只是像字符串一样添加它们。所以5 +修饰符100的值最终等于= 5100,而不是105。

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.

这是我的表格代码:

<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>

这是我的剧本:

function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;

document.getElementById("tweetsOutput").innerHTML = results;
}


推荐答案

一元加( + )将其操作数强制转换为数字:

The unary plus (+) coerces its operand into a number:

var results = +document.getElementById("addTweets").value;
    ...

typeof( results ); // number

这篇关于如何将document.getElementById值转换为整数变量,而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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