2015-12-12 24 views
0

我想用jquery函数查找复选框更改事件而不是硬编码的所有div idclass name在jquery选择器中。如何在复选框更改事件而不是在jquery选择器中硬编码div id找到div?

有我与ID名称SECTION1和第2节等chkall事件代码2节我想找到这个div ID,并通过以此为jQuery选择

这是我的代码:

HTML :

<div class="header"> 
     <asp:CheckBox ID="chkAll" CssClass="checkallparent" runat="server" Text="Select All" /> 
    </div> 
    <div class="abc"> 
     <ul class="list"> 
      <div id="section1" class="section"> 
       <li class="carousel-border"> 
        <input type="checkbox" id="chkParent1" class="chkParent" /> --Parent of below 2 checkboxes 
       </li> 
       <li> 
        <input type="checkbox" id="chkchild1" class="chkChild"/> 
       </li> 
       <li> 
        <input type="checkbox" id="chkchild2" class="chkChild"/> 
       </li> 
      </div> 

      <div id="section2" class="section"> 
       <li class="carousel-border"> 
        <input type="checkbox" id="chkParent2" class="chkParent" />--Parent of below 2 checkboxes 
       </li> 
       <li> 
        <input type="checkbox" id="chkchild3" class="chkChild" /> 
       </li> 
       <li> 
        <input type="checkbox" id="chkchild4" class="chkChild"/> 
       </li> 
      </div> 
     </ul> 
    </div> 

SCRIPT:

$(".checkallparent").change(function() { 
    //on this event i want to check all my checkboxes and this is how i am doing. 
    if ($("#chkAll").prop('checked') == true) { 
     //for section 1 
     $(this).find('input:checkbox[id^="chkParent1"]').prop('checked', true) 
     $(this).closest('.section').find('input:checkbox[id^="chkchild1"]').prop('checked', true); 
     $(this).closest('.section').find('input:checkbox[id^="chkchild2"]').prop('checked', true); 
     // Above is not working but when i do like below it is working 
     $("#section1 .chkParent").find('input:checkbox[id^="chkParent1"]').prop('checked', true) 
     $("#section1 .chkParent").closest('.section').find('input:checkbox[id^="chkchild1"]').prop('checked', true); 
     $("#section1 .chkParent").closest('.section').find('input:checkbox[id^="chkchild2"]').prop('checked', true); 

     //I dont want to hardcode like this instead i would like to use any jquery function 
     //which would find this 1st div and 2nd(for eg section1 and section2 etc...) 

    } 
}); 

那么有人可以告诉我该怎么做?

回答

1

此代码应该可以帮助您弄清楚。第一个change事件设置父级复选框,然后触发这些父母的更改事件。

第二个更改事件处理父项目。

$(".checkallparent").change(function() { 
    var checked = $(this).is(":checked"); 
    var parentCBs = $("input[type='checkbox'].chkParent"); 
    parentCBs.each(function(i, el) { 
     el.checked = checked; 
     $(el).trigger("change"); 
    }); 
}); 
$("input[type='checkbox'].chkParent").change(function() { 
    var checked = $(this).is(":checked"); 
    var div = $(this).closest("div"); 
    var childCBs = div.find("input[type='checkbox'].chkChild"); 
    childCBs.each(function(i, el) { 
     el.checked = checked; 
    }); 
}); 

Here is a working Fiddle.

+0

完美,非常感谢你 –