Select 除特定元素的最后一个复选框外的所有复选框

Select all checkbox except the last of a specific element

我想检查是否选中了特定元素的所有复选框,但最后一个 我有这种HTML

<ul class="progress-indicator">
  <li>
    //Others elements (variable)
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox"> // Exclude this one
  </li>
  <li>
    //Stuff here
  </li>
  <li>
    //Another stuff
  </li>
</ul>

我第一次尝试

if($(".progress-indicator > li:first-child").find(":checkbox").length == $(".progress-indicator > li:first-child").find(":checkbox:checked").length)
{
   //All checkbox of first li are checked
}

这是可行的,但现在我想排除第一个 li

的最后一个复选框

所以我从那个开始

$(".progress-indicator > li:first-child").find(":checkbox:not(:last-child)").length

但是没有用。这select或select只是第一个li的第一个复选框。我认为这是由于我之前的Others elements。 (例如,复选框位于 div 内,它位于另一个元素内。

那么,如何select除最后一个OF之外的第一个li的所有复选框li

做,

var last = $(".progress-indicator >li:first-child").find(":checkbox:last");

所以你的陈述将是

if($(".progress-indicator > li:first-child").find(":checkbox").not(last).length == $(".progress-indicator > li:first-child").find(":checkbox:checked").not(last).length)
{
  //All checkbox of first li are checked, regardless of the last one
}

您可以使用 eq with a negative number & not 选择器来省略最后一个元素

var x=$("input:checkbox").not(":eq(-1)");
x.each(function(){ // this part just for demo
$(this).prop("checked",true)
})

JSFIDDLE

我会使用 jQuery 的每个函数来遍历复选框。我会排除最后一个。

像这样:

$checkboxes = $('.checkbox')
lengthCheckboxes = $checkboxes.length;

$checkboxes.each(function(i,e) {
 if (i !== lengthCheckboxes - 1) 
  $(e).prop( "checked", true );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
    //Others elements (variable)
    <input class="checkbox" type="checkbox">
    <input class="checkbox" type="checkbox">
    <input class="checkbox" type="checkbox">
    <input class="checkbox" type="checkbox"> // Exclude this one
  </li>

这样就可以了。

$('.progress-indicator input[type="checkbox"]').not(':last-child').each(function(){
    $(this).prop("checked", true);
});

亲切的问候。