最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery selector: get one of multiple class names, as a string - Stack Overflow

programmeradmin1浏览0评论

I have many divs in a page, like so:

<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>

When a checkbox is checked, I want to store the value of it's parent's unique class e.g "food-6" or "food-7" in a variable. I can get all the classes of the parent, like this:

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

Which gives me formitem food-7 group-7.

How can I get "the one that starts with food-" ?

I have many divs in a page, like so:

<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>

When a checkbox is checked, I want to store the value of it's parent's unique class e.g "food-6" or "food-7" in a variable. I can get all the classes of the parent, like this:

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

Which gives me formitem food-7 group-7.

How can I get "the one that starts with food-" ?

Share Improve this question asked Oct 28, 2013 at 16:12 IlaIla 3,5488 gold badges50 silver badges78 bronze badges 1
  • 4 Since it looks like you're using this food-7 class for putation instead of CSS, have you considered using data- attributes instead? – Joe Enos Commented Oct 28, 2013 at 16:14
Add a ment  | 

3 Answers 3

Reset to default 6

Try a simple regex like

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

Use a regular expression

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

if you want just the number

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

评论列表(0)

  1. 暂无评论