javascript - 在 JavaScript 等式中使用 HTML 文本框中的数字

标签 javascript html

所以我有一些 HTML 代码:

<input type="number" id="height">

我想获取在此框中输入的任何内容并将其用作 int/float 等。假设我输入“2”。这是 JavaScript 代码:

var test;
var a;
test = document.getElementById('height').value;
a = 2 + test;

当我打印 a 时,我得到 22。这是有道理的,但我想要 4。换句话说,我希望 test 被视为 int/float(无论在文本框中输入什么)。是否有 HTML 输入类型可以为我执行此操作,或者我是否必须以其他方式更改它(如 JavaScript 命令)。

最佳答案

使用加号 (+) a.k.a unary plus 运算符作为变量赋值的第一个标记(rvalue) , test = +document.getElementById('height').value

来自developer.mozilla.org:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

工作示例

var test = +document.getElementById("height").value;
var a;

a = 2 + test;
alert(a);
<input type="number" id="height" value="5">

关于javascript - 在 JavaScript 等式中使用 HTML 文本框中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094539/

相关文章:

php - 如何使用 mPDF 库在 PDF 中并排保存两个元素?

javascript - 减小图像文件的大小以加快上传速度?

javascript - 使用 IndexOf() 过滤返回空白结果

javascript - Jquery 和 Css 以及数学 : dots in a circle to converge in one point

javascript - 如何使用RPG.JS

php - 表格数据格式化(来自数据库的数据)

html - 为什么这些 <li> 有额外的高度?

尝试禁用单选按钮时,javascript 不工作

javascript - 使用多个标记和谷歌地图 api 的中心 map

javascript - 如何提供 ECMAScript 5 (ES 5)-shim?