最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: If number above 3 digits - Stack Overflow

programmeradmin8浏览0评论

How can I see if a SPAN contains a number over 3 digits? I tried the below, but it didn't work.

    if ($('.pointScore .score').val() > 999 ) {    
        alert("Over 999 point");    
    }

Thank you in advance.

How can I see if a SPAN contains a number over 3 digits? I tried the below, but it didn't work.

    if ($('.pointScore .score').val() > 999 ) {    
        alert("Over 999 point");    
    }

Thank you in advance.

Share Improve this question asked May 4, 2011 at 9:39 curly_bracketscurly_brackets 5,59815 gold badges62 silver badges103 bronze badges 4
  • 1 Most likely .val() returns it as a string. try .val() > "999" – user176060 Commented May 4, 2011 at 9:40
  • Don't you need a cast to Integer? I'm guessing the span value is string. PerfectlyNormal's suggestion is dangerous BTW. You shouldn't pare strings with greater or less. – Vladislav Zorov Commented May 4, 2011 at 9:41
  • @PerfectlyNormal, @Vladislav: No, JavaScript does that kind of thing for you. Even gets it right, much of the time. Best to use parseInt, but possible not to. – T.J. Crowder Commented May 4, 2011 at 9:52
  • @T.J. That's why I changed "can't pare" to "shouldn't pare" before I posted the ment. – Vladislav Zorov Commented May 4, 2011 at 10:56
Add a ment  | 

3 Answers 3

Reset to default 7

You noticed that a span doesn't have a value, but there is another potential problem with the code. The text is a string, so you will be paring a string to a number. As that can have unexpected results, it should be avoided.

The easiest way is to simply check the length of the string:

if ($('.pointScore .score').text().length > 3) {    
    alert("Over 999 point");
}

You can also parse the string into a number:

if (parseInt($('.pointScore .score').text(), 10) > 999) {    
    alert("Over 999 point");
}

DOH!

I just needed to change val() to text()...

Sorry...

    if ($('.pointScore .score').text() > 999 ) {    
        alert("Over 999 point");    
    }

alternatively, you could use the length property

if ($('.pointScore .score').html().length > 3) {    
        alert("more than 3 digits");    
    }
发布评论

评论列表(0)

  1. 暂无评论