jQuery jQuery选择所有子复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14853568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery selecting all child checkboxes
提问by Andrew Rayner
Firstly, just wanted to say I am hopeless with jQuery.
首先,我只想说我对 jQuery 毫无希望。
I was looking at some code from a post on here which selects each parent checkbox (and works):
我正在查看此处的帖子中的一些代码,该代码选择每个父复选框(并有效):
$(function() {
$(":checkbox").change(function () {
$(this).parents().children(':checkbox').attr('checked', this.checked);
});
});
We have a tree view structure using <ul> <li>
and each <li>
has a checkbox.
I want to do the opposite of the above and perform the same checkbox selection on all child checkboxes.
我们有一个树视图结构<ul> <li>
,每个结构<li>
都有一个复选框。我想做与上述相反的事情,并对所有子复选框执行相同的复选框选择。
Can anyone modify the above to do that?
任何人都可以修改上述内容来做到这一点吗?
Just to note we are using razor and each checkbox is a @Html.CheckboxFor so the output is along the lines of:
请注意,我们正在使用 razor 并且每个复选框都是一个 @Html.CheckboxFor 所以输出是这样的:
<input name="Survey.Buildings[0].IsSelected" type="checkbox" value="true" checked="checked" data-val="true" data-val-required="The Selected? field is required." id="Survey_Buildings_0__IsSelected" />
<input name="Survey.Buildings[0].IsSelected" type="hidden" value="false" />
- EDIT 2:
- 编辑2:
OK I have fixed the HTML and the structure now looks like:
好的,我已经修复了 HTML,结构现在看起来像:
<ul>
<li> Cbx1
<ul>
<li> Cbx 2 </li>
</ul>
</li>
<li> Cbx3 </li>
<li> Cbx4
<ul>
<li> Cbx 5 </li>
<li> Cbx 6 </li>
</ul>
</li>
</ul>
So if Cbx4 was checked Cbx5 and 6 would be checked, and if it was unchecked they would be unchecked
因此,如果 Cbx4 被选中,Cbx5 和 6 将被选中,如果未选中,它们将不被选中
Much appreciated
非常感激
Andy
安迪
回答by nbrooks
$(function() {
$("input[type='checkbox']").change(function () {
$(this).siblings('ul')
.find("input[type='checkbox']")
.prop('checked', this.checked);
});
});
回答by tank
$(function() {
$(":checkbox").change(function () {
$(this).children(':checkbox').attr('checked', this.checked);
});
});
Not really clear with your question but you may try again by removing the parent() as shown above.
您的问题不是很清楚,但您可以通过删除 parent() 重试,如上所示。