我在一个页面中有很多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>当一个复选框被选中时,我希望将它的父类的唯一值存储在一个变量中,例如“食品-6”或“食品-7”。我可以获得父类的所有类,如下所示:
parent = $(this).closest(".formitem").attr("class");这就给了我formitem food-7 group-7。
我怎么才能得到“从食物开始的那个-”?
发布于 2013-10-29 00:14:02
尝试一个简单的正则表达式,比如
parent = $(this).closest(".formitem").attr("class").match(/\b(food-\d+)\b/)[1];发布于 2013-10-29 00:14:46
使用正则表达式
...attr("class").match(/food-\d+/)如果你只想要数字
.match(/food-(\d+)/)[0]发布于 2013-10-29 00:23:31
$(':checkbox').click(function(){
var parent_class = '';
parent_class = $(this).parent('div').attr('class').match(/food-\d+/);
alert(parent_class);
});https://stackoverflow.com/questions/19639784
复制相似问题