Javascript jQuery 将类的一部分与 hasClass 匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13878759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:01:11  来源:igfitidea点击:

jQuery match part of class with hasClass

javascriptjqueryclass

提问by ditto

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

我有几个带有“project[0-9]”类的div:

<div class="project1"></div>
<div class="project2"></div>
<div class="project3"></div>
<div class="project4"></div>

I want to check if the element has a "project[0-9]" class. I have .hasClass("project")but I'm stuck with matching numbers.

我想检查该元素是否具有“project[0-9]”类。我有,.hasClass("project")但我坚持使用匹配的数字。

Any idea?

任何的想法?

回答by Bergi

You can use the startswith CSS3 selectorto get those divs:

您可以使用startswith CSS3 选择器来获取这些 div:

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

To check one particular element, you'd use .is(), not hasClass:

要检查一个特定元素,您可以使用.is(),而不是hasClass

$el.is('[class^="project"]')

For using the exact /project\d/regex, you can check out jQuery selector regular expressionsor use

要使用确切的/project\d/正则表达式,您可以查看jQuery 选择器正则表达式或使用

/(^|\s)project\d(\s|$)/.test($el.attr("class"))

回答by Akhil Sekharan

A better approach for your html would be: I believe these div's share some common properties.

更好的 html 方法是:我相信这些 div 共享一些共同的属性。

<div class="project type1"></div>
<div class="project type2"></div>
<div class="project type3"></div>
<div class="project type4"></div>

Then you can find them using:

然后您可以使用以下方法找到它们:

$('.project')

回答by migli

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

will not fail with something like this:

不会因为这样的事情而失败:

<div class="some-other-class project1"></div>

回答by Douglas.Sesar

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

will fail with something like this:

会因为这样的事情而失败:

<div class="some-other-class project1"></div>

Here is an alternative which extends jQuery:

这是一个扩展 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)

来自 sandinmyjoints:https: //github.com/sandinmyjoints/jquery-has-attr-like/blob/master/jquery.hasAttrLike.js(但它有错误,所以我修复了它)

回答by Slavik Meltser

You can improve the existing hasClassmethod:

您可以改进现有hasClass方法:

// This is all that you need:
(orig => { 
  jQuery.fn.hasClass = function(className) {
    return className instanceof RegExp
      ? this.attr('class') && this.attr('class')
        .split(/\s+/)
        .findIndex(name => className.test(name)) >= 0
      : orig.call(this, className); 
  }
})(jQuery.fn.hasClass);

// Test the new method:
Boolean.prototype.toString = function(){ this === true ? 'true' : 'false' };
const el = $('#test');
el.append("hasClass('some-name-27822'): " + el.hasClass('some-name-27822'));
el.append("\nhasClass(/some-name-\d+/): " + el.hasClass(/some-name-\d+/));
el.append("\nhasClass('anothercoolclass'): " + el.hasClass('anothercoolclass'));
el.append("\nhasClass(/anothercoolclass/i): " + el.hasClass(/anothercoolclass/i));
el.append("\nhasClass(/^-name-/): " + el.hasClass(/^-name-/));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="test" class="some-name-0 some-name-27822 another-some-name-111 AnotherCoolClass"></pre>

回答by serhads

why don't you use for to check numbers

你为什么不用来检查数字

for (var i = 0; i < 10; i++) {
                if(....hasClass("project"+i))
                {
            //do what you need
                }
            }