检查元素是否包含数组中的任何类 [英] Check if element contains any of the class from array

查看:105
本文介绍了检查元素是否包含数组中的任何类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下要素:

<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'];

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

How do I check if any of these elements has one of the classes in the array?

推荐答案

无需循环遍历每个元素和每个类以检查它是否存在于元素上.

No need of loop over each of the element and each of the class to check it it exists on the element.

您可以按以下方式使用regex:

You can use regex as follow:

演示

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. 联接数组的所有元素
  5. ():捕获组.在这种情况下,用于匹配一个类别
  1. \b: Will match the word boundary
  2. |: Works as OR in regex
  3. arr.join('|'): Will join all the elements of array using | to join
  4. (): Capturing Group. In this case used for matching one of the class

因此,上述情况下的regex将是

So, regex in above case will be

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

这篇关于检查元素是否包含数组中的任何类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆