在我的应用程序中,我使用一个复选框来“全选”其他复选框。以下是我的代码片段,对我有用。但我需要一个更短的方法来减少我的代码行。
$('#CheckAll').change(function(){
if ($(this).is(":checked")) {
$('.checkboxes').each(function(){
$(this).prop("checked", true);
});
}
else{
$('.checkboxes').each(function(){
$(this).prop("checked", false);
});
}
});
使用“三元运算符”有没有更简单的方法来实现这一点。
答案 0 :(得分:6)
试试这个demo
$("#CheckAll").click(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
答案 1 :(得分:3)
如果确实想要使用三元运算符(fiddle):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='CheckAll'> Check all
<br><br>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
$('#CheckAll').change(function() {
if ($(this).is(":checked")) {
$('.checkboxes').prop("checked", true);
} else {
$('.checkboxes').prop("checked", false);
}
});
但是,您可以通过使用选择器(取消)选中复选框来缩短它:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='CheckAll'>Check all
<br>
<br>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
$ sudo port install thrift
答案 2 :(得分:0)
使用此:
$('#CheckAll').change(function(){
if ($(this).is(":checked")) {
$('.checkboxes').prop("checked", true);
}
else{
$('.checkboxes').prop("checked", false);
}
});
答案 3 :(得分:0)
试试这个:
var chks = $('.checkboxes'); // cache all once
$('#CheckAll').change(function(e) {
chks.prop('checked', this.checked);
});
答案 4 :(得分:0)
$('#CheckAll').change(function(){
$('.checkboxes').prop("checked",$(this).prop("checked"));
});