[英]jQuery select/unselect all siblings
I´m trying to select all siblings when first is checked.. and then if it´s unchecked all siblings should be unselected. 我试图在第一次检查时选择所有兄弟姐妹..然后如果未选中,则应取消选中所有兄弟姐妹。
but I can´t work it out so any pointers are welcome :) 但我不能解决它所以欢迎任何指针:)
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<ul>
<li><input id="checkall" type="checkbox" />Select all</li>
<li><input type="checkbox" />Child 1</li>
<li><input type="checkbox" />Child 2</li>
<li><input type="checkbox" />Child 3</li>
<li><input type="checkbox" />Child 4</li>
</ul>
<script type="text/javascript">
//clicking the first checkbox should check or uncheck all checkboxes in that element
$(document).ready(function(){
$('#checkall').click(function(){
if ($(this).closest('ul').find('input:checkbox').attr('checked', false)) {
$(this).closest('ul').find('input:checkbox').attr('checked', true)
}
else ($(this).closest('ul').find('input:checkbox').attr('checked', true)); {
$(this).closest('ul').find('input:checkbox').attr('checked', false)
}
});
});
</script>
Pretty basic: 很基本的:
$('#checkall').click(function(){
//select ul
$(this).closest('ul')
//find checkbox
.find('> li > input[type=checkbox]') //or : input[type=checkbox]
//not first check - is the 'select all'
.not(':first')
//set value
.prop('checked', this.checked)
});
Or short: 或者简短:
$('#checkall').click(function(){
$(this).closest('ul').find('> li > input[type=checkbox]').not(':first').prop('checked', this.checked)
});
.attr('checked', false)
will set the 'false` value to checked property of the element and not return a boolean value. .attr('checked', false)
将'false`值设置为元素的checked属性,而不返回布尔值。 You can simplify you code like this. 您可以像这样简化代码。
$(document).ready(function(){
$('#checkall').click(function(){
$(this).closest('ul').find(':checkbox').attr('checked', this.checked);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.