所以我有一些 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/