我正在尝试设置onClick on href,它可以选择所有复选框,但是我的代码能够选择所有复选框,但是如果再次选中onClick按钮,如何取消选中复选框呢?敬请指教。
HTML
<input type="checkbox" name="fool1" id="fool1">
<input type="checkbox" name="fool2" id="fool2">
<a href="#" class="action_link padding-10" id="selectAll" value="selectAll">全选</a> jQuery
$(document).ready(function() {
$('#selectAll').click(function() {
$("input:checkbox").attr('checked', true);
});
});发布于 2016-10-10 02:18:35
许多jQuery方法,包括.attr()和.prop(),允许您传递一个回调函数,而不是要设置的值。回调接收要更改的属性的当前值,并应返回新值。通过这种方式,您可以为正在更新的集合中的每个元素设置不同的值,具体取决于它们各自的起始值。
注意,一般来说,在更新checked属性时,最好使用.prop()而不是.attr()。
所以:
$(document).ready(function() {
$('#selectAll').click(function(e){
e.preventDefault();
$("input:checkbox").prop('checked', function(i, current) { return !current; });
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="fool1" id="fool1">
<input type="checkbox" name="fool2" id="fool2">
<a href="#" class="action_link padding-10" id="selectAll" value="selectAll">全选</a>
请注意,我所展示的代码分别反转复选框,它没有将所有复选框都设置为相同的值。因此,如果用户只手动设置了一些复选框,那么单击锚就不会将它们全部设置为相同。
发布于 2016-10-10 02:24:30
用道具代替阿塔尔。试着做这样的事:
$(document).ready(function() {
$('#selectAll').click(function() {
var $checkbox = $('input:checkbox');
$checkbox.prop('checked', !$checkbox.prop('checked'));
});
});发布于 2016-10-10 02:25:00
您应该使用而不是attr。见这里。
$(input[type=checkbox]).prop('checked', true)。
根据您想要实现的目标,您需要跟踪复选框的当前状态。
#selectAll只保留当前状态的全局var checked,然后将其更改为相反的状态,并相应地更新所有复选框。#selectAll2跟踪检查了多少复选框--如果所有复选框都被选中--假设您想取消选中它们,如果至少选中了一个复选框,那么其目的是检查所有复选框。否则就会表现为第一个例子。因此,这可能取决于您的意图/用户体验。
参见此示例:
$(document).ready(function() {
var checked = false;
$('#selectAll').click(function(){
checked = !checked;
$("input[type=checkbox]").prop('checked', checked);
});
var numChecks = $("input[type=checkbox]").length;
var checked2 = false;
$('#selectAll2').click(function() {
var chked = $("input[type=checkbox]:checked").length;
var allChecked = chked == numChecks;
var anyChecked = chked > 0;
if(allChecked) {
checked2 = false;
} else if(anyChecked) {
checked2 = true;
} else {
checked2 = !checked2;
}
$("input[type=checkbox]").prop('checked', checked2);
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="fool1" id="fool1">
<input type="checkbox" name="fool2" id="fool2">
<a href="#" class="action_link padding-10" id="selectAll" value="selectAll">全选</a>
<a href="#" class="action_link padding-10" id="selectAll2">全选</a>
https://stackoverflow.com/questions/39950453
复制相似问题