[英]jQuery traversing parent and children
I have a nested unsorted list and I want to place a click event on the parent checkbox so when it is check it checks all the children checkboxes and vice versa. 我有一个嵌套的未排序列表,我想在父复选框上放置一个click事件,因此当选中它时,它会检查所有子复选框,反之亦然。 For some reason I can only get the selector to get all inputs of type check box... ive tried a variety or ways, this is one of them.
由于某种原因,我只能使选择器获得类型复选框的所有输入...我尝试了多种方式,这就是其中一种。 any suggestions ?
有什么建议么 ?
<ul id="parent">
<li>
<input type='checkbox'>first</input>
<ul>
<li><input type='checkbox'>child1</input>
</li>
<li><input type='checkbox'>child2</input>
</li>
</ul>
</li>
<li>
<input type='checkbox'>second</input>
<ul>
<li><input type='checkbox'>child1</input>
</li>
<li><input type='checkbox'>child2</input>
</li>
</ul>
</li>
</ul>
jQuery jQuery的
$('#parent > li input[type=checkbox]').click(function() {
var parent = $(this);
if ($(parent).is(':checked')) {
$('li > input[type=checkbox]', parent).each(function() {
$(this).attr('checked', true);
});
}
else {
$('li > input[type=checkbox]', parent).each(function() {
$(this).attr('checked', false);
});
}
});
This should work: 这应该工作:
First you go back to the LI and than you search for the checkboxes 首先,您返回到LI,然后搜索复选框
$('#parent > li input[type=checkbox]').click(function() {
$(this).closest("li").find("ul li input[type=checkbox]").attr('checked', $(this).is(':checked'))
});
However you might consider adding some class names. 但是,您可以考虑添加一些类名。 So your code becomes more readable.
因此,您的代码更具可读性。
<li>
<input type='checkbox' class='category'>first</input>
<ul>
<li><input type='checkbox' class='subcategory'>child1</input>
</li>
<li><input type='checkbox' class='subcategory'>child2</input>
</li>
</ul>
</li>
Than your jQuery would look like this: 比您的jQuery看起来像这样:
$("#parent .category").click(function(){
$(this).closest("li").find(".subcategory").attr('checked', $(this).is(':checked'))
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.