我有一个带有多个复选框的表。每次我选中或取消选中复选框时,它都会调用一个函数,将参数作为模型发送到 Controller 以更新数据库。现在我想选中/取消选中全部,做同样的事情。我可以选中/取消选中它们,但该函数没有被调用。
复选框
<input id="Include" class="checkBoxClass" type="checkbox" @(item.Include != "1" ? null : "checked")>
将模型发送到 Controller 的函数
$('input:checkbox').change(function () {
var tr = $(this).parents('tr:first');
var Id = document.getElementById('Id').value;
(...)
var UserModel =
{
"Id": Id,
(...)
};
$.ajax({
url: '@Url.Action("Action","Controller")',
type: 'POST',
data: JSON.stringify(UserModel),
contentType: 'application/json; charset=utf-8',
success: function () {
}
});
});
我选中/取消选中所有代码
$('#ckbCheckAll').click(function (event) {
$('.checkBoxClass').each(function () {
if (!this.checked)
{
$('.checkBoxClass').each(function () {
$('.checkBoxClass').click("checked", true);
});
} else {
$('.checkBoxClass').each(function () {
$('.checkBoxClass').click("checked", false);
});
}
});
});
当我单击#ckbCheckAll按钮时,所有复选框都被选中/取消选中,但即使我在“将模型发送到 Controller ”功能上有.change,它也不起作用。
- 我在这里做错了什么?
- 这样做可靠吗?
最佳答案
用简单的英语来说,对于全选按钮,如果单击了所有复选框,则检查(if)和每个(.each())复选框,如果该框被选中,则伪造单击(.click())以取消选中它,
$('input[type=checkbox]').change(function(){/*alert('change')*/});
$('.checkall').click(
function() {
$('input[type=checkbox]').each(function(index,el){
if(!this.checked) {
$(el).click(); // check all box;
}
});
}
);
$('.uncheckall').click(
function() {
$('input[type=checkbox]').each(function(index,el){
if(this.checked) {
$(el).click(); // uncheck all box;
}
});
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="button" value="check all" class='checkall'/>
<input type="button" value="uncheck all" class='uncheckall'/>
关于javascript - 为全选/取消全选时的每个复选框调用 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31209757/