首页 > 解决方案 > 获取变量形式部分类选择器jQuery

问题描述

您如何将类选择器的剩余部分存储为 foreach 循环的变量

例如:

<div class="sel_child1">something</div>
<div class="sel_child2">something</div>

我知道我可以教派:

jQuery( "[class^='sel_']" )

但我需要 foreach 循环的其余部分,因为类的第二部分是要定位的子元素,在你问之前我知道我应该使用数据属性或其他方法,但我使用的 CMS 不会让我这样做。

也有可能 div 有其他不相关的类。

标签: jquery

解决方案


.attr("class")您可以使用该方法获取整个类字符串。从那里开始,将其分解为一个类列表,找到以 开头的类"sel_",然后存储第二个部分。

$("[class*='sel_']").each(function() {     //match all classes with sel_ in them
  const child = $(this)         
    .attr("class")                         //get the class string
    .split(" ")                            //break it into individual classes
    .find(n => n.startsWith("sel_"))       //find the one that starts with sel_
    .split("_")[1];                        //split it on _ and take the second piece

  console.log(child);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sel_child1 unrelated">something</div>
<div class="unrelated sel_child2">something</div>

还有一个更简洁的 RegEx 替代方案......

$("[class*='sel_']").each(function() {
  const child = $(this).attr("class").match(/(?:^|\s)sel_([^\s]*)/)[1];
  console.log(child);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sel_child1 unrelated">something</div>
<div class="unrelated sel_child2 xsel_child3">something</div>


正则表达式参考

(?:^|\s)- 字符串空格的开头(非捕获)

sel_- “sel_”

([^\s]*)- 直到下一个空格的所有内容(捕获)


推荐阅读