Javascript 如何将 HTML 输入值的数据类型更改为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5327179/
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 can I change an HTML input value's data type to integer?
提问by ptamzz
I'm using jQuery to retrieve a value submitted by an input button. The value is supposed to be an integer. I want to increment it by one and display it.
我正在使用 jQuery 来检索输入按钮提交的值。该值应该是一个整数。我想将它加一并显示它。
// Getting immediate Voting Count down button id
var countUp = $(this).closest('li').find('div > input.green').attr('id');
var count = $("#"+countUp).val() + 1;
alert (count);
The above code gives me a concatenated string. Say for instance the value is 3. I want to get 4 as the output, but the code produces 31.
上面的代码给了我一个连接的字符串。例如说值是 3。我想得到 4 作为输出,但代码产生 31。
How can I change an HTML input value's data type to integer?
如何将 HTML 输入值的数据类型更改为整数?
回答by Alnitak
To convert strValue
into an integer, either use:
要转换strValue
为整数,请使用:
parseInt(strValue, 10);
or the unary +
operator.
或一元运算+
符。
+strValue
Note the radix parameter to parseInt
because a leading 0 would cause parseInt
to assume that the input was in octal, and an input of 010
would give the value of 8 instead of 10
注意 radix 参数,parseInt
因为前导 0 会导致parseInt
假设输入是八进制的,而输入 of010
会给出值 8 而不是 10
回答by Quentin
parseInt( $("#"+countUp).val() , 10 )
回答by justkt
Use parseInt as in: var count = parseInt($("#"+countUp).val(), 10) + 1;
or the +
operator as in var count = +$("#"+countUp).val() + 1;
使用 parseInt as in:var count = parseInt($("#"+countUp).val(), 10) + 1;
或+
操作符 invar count = +$("#"+countUp).val() + 1;
回答by Landern
var count = parseInt(countUp, 10) + 1;
See w3schools webpage for parseInt.
有关parseInt ,请参阅w3schools 网页。