【问题标题】:jquery if element contains numberjquery如果元素包含数字
【发布时间】:2014-01-13 11:16:16
【问题描述】:

我想知道一个元素是否包含一个数字,不管它有多长。我需要区分单词和数字或其他字符。

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>

【问题讨论】:

标签: jquery numbers


【解决方案1】:

您可以为此使用isNumeric 函数。

demo

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

demo

【讨论】:

    【解决方案2】:

    您也可以使用 REGEX 来做到这一点

    正则表达式 '/\d/'

    $(this).text().match(/\d/)

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

    Fiddle

    【讨论】:

      【解决方案3】:

      试试这个。使用isNaN 判断是否为数字。

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

      【讨论】:

        【解决方案4】:

        正如 C-link 所说,isNumeric..

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

        【讨论】:

          【解决方案5】:
          $( "li a" ).each(function() {
          
          var xc = $(this).text();
          
            if ( $.isNumeric(xc) ) {
              $(this).attr('class', 'numb');
            } else {
          $(this).attr('class', 'noNumb');
            }
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-02-17
            • 1970-01-01
            • 1970-01-01
            • 2016-04-09
            • 1970-01-01
            • 1970-01-01
            • 2014-12-05
            相关资源
            最近更新 更多