jQuery获取文本作为数字(jQuery get text as number)

98 IT屋

This code doesn't work:

var number = $(this).find('.number').text();
var current = 600;
if (current > number){
     // do something
}

HTML:

<div class="number">400</div>

Seems there is some problem with converting text() from text-like value to number.

What is the solution?

解决方案

Always use parseInt with a radix (base) as the second parameter, or you will get unexpected results:

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 zero NaN which can be tested with the function isNaN() if it's an invalid number:

var number = +($(this).find('.number').text());

此代码不起作用:



  var number = $(this).find ('.number')。text(); 
var current = 600;
if(当前>数字){
//做某事
}


HTML:



 < div class = number> 400< / div> 


似乎转换 text()从类似文本的值到数字。



解决方案是什么?


解决方案

始终使用带有基数(基数)的 parseInt 作为第二个参数,否则您将得到意外的结果:



  var number = parseInt($(this).find('。number')。text(),10); 


一个流行的变体是使用 + 作为单一运营商。这将始终以10为底进行转换,并且永远不会引发错误,只需返回 NaN 即可使用函数进行测试isNaN()如果它是无效数字:



  var number = +($(this)。 find('。number')。text()); 

本文地址:IT屋 » jQuery获取文本作为数字