【发布时间】:2021-08-16 05:55:19
【问题描述】:
我在这里尝试修复一个 JS 函数。单击“检查全部”按钮时会触发此功能。单击此按钮时,应选中并禁用表中的所有项目。当我运行此功能并单击 Check All 按钮时,所有项目都被短暂选中,然后它们又回到未选中状态。我做错了什么?
PS:我尝试添加 e.preventDefault() 和末尾 功能和它不起作用
$(document).ready(function () {
$('body').on('change', '#checkAll', function (e) {
if(this.checked){
let boxes = $("input.promo-action-checkbox");
boxes.toArray().forEach(element => {
console.log(element);
$(element).attr('disabled', 'disabled');
var name = $(element).data('name');
var number = $(element).data('number');
var user = $(element).data('user');
$.ajax({
method: 'post',
url: '/checker',
contentType: "application/json",
data: JSON.stringify({
name: name,
number: number,
user: user
}),
dataType: 'json',
error: function () {
$(element).attr('disabled', '');
}
})
});
html表格中的列是如何组成的:
var table = $('#datatable').DataTable({
pageLength: 20,
lengthChange: false,
language: {
paginate: {
previous: '<i class=\'fas fa-angle-left\'>',
next: '<i class=\'fas fa-angle-right\'>'
}
},
ordering: true,
processing: true,
serverSide: true,
ajax: {
url: '/table/',
dataSrc: 'results'
},
columns: [
{
data: null,
render: function (data, type, row, meta) {
let rowHtml = '<div class="custom-control custom-checkbox mb-3"> <input class="custom-control-input promo-action-checkbox" id="checkbox-' + meta.row + '" data-name="' + row.name + '" data-phone="' + row.number + '" data-admin="' + row.user + '" type="checkbox"'
if (row.fulfilled) {
rowHtml += ' disabled checked'
}
rowHtml += '> <label class="custom-control-label" for="checkbox-' + meta.row + '"></label></div>'
return rowHtml
}
},
{
searchable: true,
data: 'name'
}
]
});
这是可行的,但是“checkAll”框没有被勾选。此表也不在表单内。
$('#checkAll').click(function (e) {
e.preventDefault()
$('input.action-checkbox').prop('checked', this.checked);
$('input.action-checkbox').prop('disabled', true);
return false;
})
表结构:
<div class="table-responsive">
<table class="table align-items-center table-flush table-striped" id="datatable-promo-code">
<thead class="thead-light">
<tr>
<th>Check All <input id = "checkAll" type= "checkbox"></th>
<th>Name</th>
<th>Info</th>
<th>address</th>
<th>Email</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
【问题讨论】:
-
请添加所有相关代码(HTML、CSS 和 JavaScript),以便我们复制您的问题。
-
@ScottMarcus 我刚刚更新了它
-
您的 ajax 调用一定失败了,因为
error函数是重新启用它们的原因。您正在传递datatype: 'json',因此无需调用stringify,jQuery 会为您执行此操作,只需直接传递 json 对象即可。至于他们为什么不勾选,不知道,没有相关的代码。 -
现在,我不介意他们被禁用。我只希望 ClickAll 按钮检查并禁用所有其他按钮并保持这种状态,直到我手动刷新页面
-
检查你的 if(this.checked) 语句被调用了多少次。我之所以这么说,是因为在将事件处理程序多次绑定到同一个对象之前,我在使用 JQuery On 方法时遇到了问题。
标签: javascript html jquery node.js ajax