jQuery获取文本作为数字 [英] jQuery get text as number

查看:421
本文介绍了jQuery获取文本作为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码无效:

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

HTML:

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

似乎将text()从类似文本的值转换为数字时存在一些问题.

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

什么解决方案?

推荐答案

始终将parseInt与基数(基数)一起用作第二个参数,否则您将得到意外的结果:

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);

但是,一个流行的变体是将+用作统一运算符.这将始终以10为底进行转换,并且永远不会抛出错误,只需返回 NaN,如果该数字无效,则可以使用函数isNaN()对其进行测试:

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());

这篇关于jQuery获取文本作为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆