【问题标题】:Check if element contains any of the class from array检查元素是否包含数组中的任何类
【发布时间】:2015-07-13 14:05:01
【问题描述】:

我有以下元素:

<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight ten"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight eleven"></div> 
<div class="one two three four five six seven eight nine"></div>

还有下面的JS:

var obj = ['nine', 'ten', 'eleven'];

如何检查这些元素中的任何一个是否具有数组中的类之一?

【问题讨论】:

  • 笛卡尔检查!哇! :P
  • “检查”是什么意思?您是否只想选择数组中包含某个类的所有 div?
  • 如果你真的要检查,那么api.jquery.com/hasclass 将在某处使用
  • 这样? JsFiddle

标签: javascript jquery


【解决方案1】:

无需遍历每个元素和每个类来检查它是否存在于元素上。

您可以使用regex,如下:

Demo

var arr = ['nine', 'ten', 'eleven'];
var classes = '\\b(' + arr.join('|') + ')\\b',
  regex = new RegExp(classes, 'i');


$('div').each(function() {
  var elClasses = ' ' + $(this).attr('class').replace(/\s+/, ' ') + ' ';
  if (regex.test(elClasses)) {
    $(this).addClass('valid');
  }
})
div {
  color: red;
}
.valid {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight ten">Valid Ten</div>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight eleven">Valid 11</div>
<div class="one two three four five six seven eight nine">Valid 9</div>

正则表达式解释

  1. \b: 会匹配单词边界
  2. |:在正则表达式中用作 OR
  3. arr.join('|'):将使用|加入数组的所有元素
  4. ():捕获组。在这种情况下,用于匹配其中一个类

所以,regex 在上述情况下将是

/\b(nine|ten|eleven)\b/

【讨论】:

  • 最好的之一! :)
  • jQuery 核心中已经存在的功能的代码膨胀
  • 它匹配任何东西,例如tentacles 将是一个有效的类。添加边界会有所帮助,但是使用正则表达式匹配类,尤其是多个类,会出现问题。
  • @adeneo 感谢您指出错误。请参阅 jsfiddle.net/tusharj/kumph75c/4。我也更新了答案
【解决方案2】:
function checkClasses () {
    var tagsWithClasses = [];
    $.each($("div"), function( index, value ){
         for (i=0; i<obj.length; i++) {
              if ($(value).hasClass(obj[i])) {
                    tagsWithClasses.push($(value));
                    continue;
              }
         }
    });

    return tagsWithClasses;
}

【讨论】:

    【解决方案3】:
    $('div').each(function () {
        var found = false;
        var element_classes = $(this)[0].className.split(/\s+/);
    
        // Loop each class the element has
        for (var i = 0; i < element_classes.length; i++) {
            // Check if each class from the element is within the array of classes we want to match
            if (['nine', 'ten', 'eleven'].indexOf(element_classes[i]) !== -1) {
                // We found a match, break out of the loop
                found = true;
                break;
            }
        }
    
        // check if found or not
        if (found) {
            // Was found
        }
        else {
            // Was not found
        }
    
    });
    

    【讨论】:

      【解决方案4】:
      var obj = ['nine', 'ten', 'eleven'];
      var divs =[];
      $.each(obj,function(key,value){
      
        var values = value;
        $(div).each(function(){
        var divId = $(this).attr('id');  // Giving some separate id for the div to track it
        var getClass = $(this).attr('class');
      
        if(getClass.indexOf(values) >= 0) {
          div.push("divId");
        }
       });
      });
      

      你可以循环遍历元素和结果

      【讨论】:

        【解决方案5】:

        如何检查这些元素中的任何一个是否具有 数组

        你必须遍历元素和类,并检查每个元素是否包含数组中的任何类,像这样

        var elements = $('div');
        var obj      = ['nine', 'ten', 'eleven'];
        
        var hasClass = elements.filter(function(index, elem) {
            return obj.some(function(klass) {
                return elem.classList.contains(klass);
            });
        }).length > 0;
        

        你可以很容易地把它变成一个函数

        function hasClass(elements, classes) {
            return elements.filter(function(index, elem) {
                return classes.some(function(klass) {
                    return elem.classList.contains(klass);
                });
            }).length > 0;
        }
        

        FIDDLE

        使用Array.someElement.classList.contains 避免不必要的迭代和类名的缓慢匹配。

        【讨论】:

          【解决方案6】:

          问题取决于您要做什么。

          如果您尝试创建这些元素的集合,您可以从数组中创建一个选择器:

          var elemCollection = $(  '.' + obj.join(',.') ).doSomething();
          

          也可用于filter()

          $existingElementCollection.filter(  '.' + obj.join(',.') ).doSomething();
          

          或者可以用在is()

          var filterSelector =  '.' + obj.join(',.');
          $someCollection.each(function(){
             if($(this).is( filterSelector ){
               // do somthing for matches
             }
          });
          

          DEMO

          【讨论】:

            猜你喜欢
            • 2016-10-13
            • 1970-01-01
            • 2016-09-22
            • 2017-11-24
            • 1970-01-01
            • 1970-01-01
            • 2021-05-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多