jQuery match part of class with hasClass

前端 未结 6 2286
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 20:37

I have several div\'s with \"project[0-9]\" classes:

6条回答
  •  -上瘾入骨i
    2020-12-01 21:23

    $('div[class^="project"]')
    

    will fail with something like this:

    Here is an alternative which extends jQuery:

    // Select elements by testing each value of each element's attribute `attr` for `pattern`.
    
      jQuery.fn.hasAttrLike = function(attr, pattern) {
    
        pattern = new RegExp(pattern)
        return this.filter(function(idx) {
          var elAttr = $(this).attr(attr);
          if(!elAttr) return false;
          var values = elAttr.split(/\s/);
          var hasAttrLike = false;
          $.each(values, function(idx, value) {
            if(pattern.test(value)) {
              hasAttrLike = true;
              return false;
            }
            return true;
          });
          return hasAttrLike;
        });
      };
    
    
    
    jQuery('div').hasAttrLike('class', 'project[0-9]')
    

    original from sandinmyjoints: https://github.com/sandinmyjoints/jquery-has-attr-like/blob/master/jquery.hasAttrLike.js (but it had errrors so I fixed it)

提交回复
热议问题