2014-01-13 65 views
0

我想知道元素是否包含数字,不管它多长时间。我需要区分单词和数字或其他字符。jQuery如果元素包含数字

fiddle

<ul> 
    <li><a href="#">Word</a></li> <!-- this is a word --> 
    <li><a href="#">1</a></li> 
    <li><a href="#">2</a></li> 
    <li><a href="#">...</a></li> <!-- this is a word --> 
    <li><a href="#">15</a></li> 
    <li><a href="#">30</a></li> 
    <li><a href="#">100</a></li> <!-- this is a number --> 
    <li><a href="#">Word</a></li> 
</ul> 
+0

http://jsfiddle.net/4P9CC/3/ – softsdev

回答

4

您可以使用isNumeric函数。

demo

$("li a").each(function() { 
var num = $(this).text(); 
if ($.isNumeric(num)) { 
     $(this).addClass('numb'); 
    } else { 
     $(this).addClass('noNumb'); 
    } 
}); 

demo

1

尝试了这一点。使用isNaN来检查它是否是一个数字。

$("li a").each(function() { 
    var xc = $(this).text(); 
    var isNum = isNaN(xc); 
    if (isNum) { 
      $(this).attr('class', 'numb'); 
     } else { 
      $(this).attr('class', 'noNumb'); 
     } 
}); 
0

为C-链接说,ISNUMERIC ..

$("li a").each(function() { 
var toCheck = $(this).text(); 
if (isNumeric(toCheck)) { 
     $(this).attr('class', 'is_number'); 
    } else { 
     $(this).attr('class', 'is_not_number'); 
    } 
}); 
0

您还可以通过使用正则表达式

做到这一点

Reguler EXP“/\ d/ '

$(本)的.text()。匹配(/ \ d /)

$("li a").each(function() { 
    var matches = $(this).text().match(/\d/); 
    if (matches){ 
     $(this).attr('class', 'numb');  
    }else{ 
     $(this).attr('class', 'noNumb');  
    } 
}); 

Fiddle

0
$("li a").each(function() { 

var xc = $(this).text(); 

    if ($.isNumeric(xc)) { 
    $(this).attr('class', 'numb'); 
    } else { 
$(this).attr('class', 'noNumb'); 
    } 
}); 
相关问题