jquery - 获取变量形式部分类选择器jQuery
问题描述
您如何将类选择器的剩余部分存储为 foreach 循环的变量
例如:
<div class="sel_child1">something</div>
<div class="sel_child2">something</div>
我知道我可以教派:
jQuery( "[class^='sel_']" )
但我需要 foreach 循环的其余部分,因为类的第二部分是要定位的子元素,在你问之前我知道我应该使用数据属性或其他方法,但我使用的 CMS 不会让我这样做。
也有可能 div 有其他不相关的类。
解决方案
.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]*)
- 直到下一个空格的所有内容(捕获)
推荐阅读
- vb.net - vb.net在以最大化形式绘制线条(使用XNA)时避免放大图片框
- python - 拥抱脸:NameError:未定义名称“句子”
- c++ - QT - Lambda-Capture by reference - qmlRegisterSingletonType
- pytest - Pytest:将多个参数传递给夹具
- r - Global Moran's I in R 使用 spdep 包
- python-3.x - Tkinter 条件格式:如果先前的值不相等,则更改颜色?
- java - 如何在spring boot中发送多个requestparams
- c - 使用 SPI for Postgres 时如何拆分记录(用于扩展)
- node.js - BEP-20 代币交易中被低估的交易
- flutter - 我将我的 shell 切换为 fish 并且我的颤动命令被破坏了。我该如何解决?