我想使用 jquery 函数查找复选框更改事件上的所有 div,而不是在 jquery 选择器中硬编码 id 和 class 名称。
我的代码中有 2 个部分,其 ID 名称为“section1”和“section2”,依此类推,在 chkall 事件中,我想找到此 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>
脚本:
$(".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... )
}
});
有人能告诉我该怎么做吗?
最佳答案
这段代码应该可以帮助你弄清楚这一点。第一个 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;
});
});
关于javascript - 如何在复选框更改事件上查找 div 而不是在 jquery 选择器中硬编码 div id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34236596/