jQuery 获取文本作为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3546900/
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
jQuery get text as number
提问by James
This code doesn't work:
此代码不起作用:
var number = $(this).find('.number').text();
var current = 600;
if (current > number){
// do something
}
HTML:
HTML:
<div class="number">400</div>
Seems there is some problem with converting text()
from text-like value to number.
text()
从类似文本的值转换为数字似乎存在一些问题。
What is the solution?
解决办法是什么?
回答by RoToRa
Always use parseInt
with a radix (base) as the second parameter, or you will get unexpected results:
始终使用parseInt
基数(基数)作为第二个参数,否则会得到意想不到的结果:
var number = parseInt($(this).find('.number').text(), 10);
A popular variation however is to use +
as a unitary operator. This will always convert with base 10 and never throw an error, just return zeroNaN
which can be tested with the function isNaN()
if it's an invalid number:
然而,一种流行的变体是+
用作酉运算符。这将始终以 10 为基数进行转换并且永远不会抛出错误,只返回零NaN
,isNaN()
如果它是无效数字,则可以使用该函数进行测试:
var number = +($(this).find('.number').text());
回答by Trimack
myInteger = parseInt(myString);
myInteger = parseInt(myString);
It's a standard javascript function.
这是一个标准的 javascript 函数。
回答by Matt
Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)
使用 javascript parseInt 方法(http://www.w3schools.com/jsref/jsref_parseint.asp)
var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
// do something
}
Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.
不要忘记指定 10 的基数值,它告诉 parseInt 它以 10 为底。
回答by Thizzer
var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
// do something
}
回答by Nilks
number = parseInt(number);
That should do the trick.
这应该够了吧。
回答by Tony L.
If anyone came here trying to do this with a decimal like me:
如果有人来这里试图用像我这样的小数来做到这一点:
myFloat = parseFloat(myString);
myFloat = parseFloat(myString);
If the just need an Int, that's well covered in the other answers.
如果只需要一个 Int,其他答案中已经很好地涵盖了这一点。