JQuery 选择器:以字符串形式获取多个类名之一

JQuery selector: get one of multiple class names, as a string

本文关键字:获取 选择器 字符串 JQuery      更新时间:2023-09-26

>我在一个页面中有很多div,如下所示:

<div class="formitem food-6 group-7">
//content of div
  <input type="checkbox"> //child of div
</div>
<div class="formitem food-7 group-7">
//content of div
  <input type="checkbox"> //child of div
</div>

选中复选框后,我想将其父级唯一类的值存储在变量中,例如"food-6"或"food-7"。我可以获取父级的所有类,如下所示:

parent = $(this).closest(".formitem").attr("class");

这给了我formitem food-7 group-7.

我怎样才能得到"从食物开始的那个——"?

尝试一个简单的正则表达式,例如

parent = $(this).closest(".formitem").attr("class").match(/'b(food-'d+)'b/)[1];

使用正则表达式

...attr("class").match(/food-'d+/)

如果你只想要号码

.match(/food-('d+)/)[0]
$(':checkbox').click(function(){
    var parent_class = '';
    parent_class = $(this).parent('div').attr('class').match(/food-'d+/);
    alert(parent_class);
});