jquery获取所选复选框的索引

时间:2012-06-06 15:50:19

标签: javascript jquery

我有一些像这样的HTML:

<div id="Myclass">

 <div class="Wrapper">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
 </div>

 <div class="Wrapper">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
 </div>

</div>

我想找到所选文本框的索引(如果有)。

现在,我写了这个:

$('#MyClass .Wrapper').each(function () {

    Index = 0;

    $(this).find('.SomeCheckboxClass').each(function () {
        if ($(this).attr('checked')) {
            Index = $(this).index();
        }
    });

    SomeFunction(Index);
});

有更好的方法吗?

感谢。

3 个答案:

答案 0 :(得分:5)

您可以使用.maphttp://jsfiddle.net/p4nD7/1/

$("#Myclass .Wrapper :checkbox:checked").map(function() {
  return $(this).index();  // index in parent
}).each(function() {
  "use strict";  // no object for `this` but just the primitive value
  SomeFunction(this);
});

答案 1 :(得分:1)

$('#Myclass .Wrapper').each(function() {
    var Index = $('.SomeCheckboxClass:checked', this).index();
    SomeFunction(Index);
});

<强> ​DEMO

您也可以使用map()

$('#Myclass .Wrapper').map(function() {
    var Index = $('.SomeCheckboxClass:checked', this).index();
    SomeFunction(Index);
});

<强> DEMO

答案 2 :(得分:0)

为什么不这样做:

$('.checkbox').click(function() {
    if($(this).attr('checked')) {
        SomeFunction($(this).index());
    }
});
相关问题