我正在使用jQuery DataTables显示我需要的数据。该表的行将根据数据而变化。当用户单击该行时,将选择该行。我的表已使用ajax.reload()
重新加载。问题是当重新加载表时,选定的行将被取消选择。
我创建了一个代码,当用户单击<tr>
时,背景颜色将改变。然后将行的ID存储到变量中。重新加载数据表后,我使用contains()
检查表中是否存在ID,然后尝试添加指示其已选择的类。
我的HTML:
<table id="messageDt" class="table table-no-bordered table-hover display" cellspacing="0" width="100%" style="width:100%">
<thead>
<tr>
<th>Contact</th>
<th>Messages</th>
<th>Date Received</th>
<th>Message Status</th>
<th>Port ID</th>
<th>Has Read</th>
<th>Assigned To</th>
</tr>
</thead>
</table>
DataTable初始化代码:
var convoTable = $('#messageDt').DataTable({
"dom": 'lfrtip',
"responsive": true,
"bPaginate": true,
"bLengthChange": false,
"scrollCollapse": true,
"order": [2, 'desc'],
"stripeClasses": [],
select: true,
"ajax": "smsSenders.json",
"aoColumns": [{
"mData": function (data, type, dataToSet) {
var contactName = data.contactName;
var sender = data.sender;
if (contactName === null) {
if (sender.length > 20) {
return sender.substr(0, 20) + '...';
} else {
return sender.substr(0, 20);
}
} else {
if (contactName.length > 20) {
return contactName.substr(0, 20) + '...';
} else {
return contactName.substr(0, 20);
}
}
}
}, {
"mData": function (data, type, dataToSet) {
var contentM = data.content;
if (contentM === null) {
return contentM = " ";
} else {
contentM = data.content;
if (contentM.length > 30) {
return contentM.substr(0, 30) + '...';
} else {
return contentM.substr(0, 30);
}
}
}
}, {
"mData": "receiveTime"
}, {
"mData": "messageStatus"
}, {
"mData": "portId"
}, {
"mData": "hasRead"
}, {
"mData": "isAssignedToTicket",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
if (oData.isAssignedToTicket === null) {
$(nTd).html("<p>None</p>");
} else {
$(nTd).html("<a class='linkColor' href='${pageContext.request.contextPath}/cnr/viewEditTicket?ticketNumber=" + oData.isAssignedToTicket + "'>" + oData.isAssignedToTicket + "</a>");
}
}
}
],
"createdRow": function (row, data, dataIndex) {
if (data.hasRead === "0") {
$(row).addClass('noRead');
} else {
$(row).addClass('yesRead');
}
if (data.messageStatus == "0") {
$(row).addClass('messageNotSent');
}
},
language: {
"search": "_INPUT_",
searchPlaceholder: "Search message"
}
});
$('[rel="tooltip"]').tooltip();
convoTable.column(3).visible(false);
convoTable.column(4).visible(false);
convoTable.column(5).visible(false);
行“点击”处理程序:
$('#messageDt tbody').on('click', 'tr', function () {
if ($(this).hasClass('isSelected')) {
$(this).removeClass('isSelected');
} else {
$('#messageDt tr.isSelected').removeClass('isSelected');
$(this).addClass('isSelected');
}
var currentRow = $(this).closest("tr");
var data = $('#messageDt').DataTable().row(currentRow).data();
var sender = encodeURIComponent(data['sender']);
senderTmp = data['sender'];
var contactName = data['contactName'];
contactNameTmp = contactName;
portIdTmp = data['portId'];
messageIdTmp = data['messageId'];
var dateR = data['receiveTime'];
var smsc = data['smsc'];
contentTmp = data['content'];
typeOfMessageTmp = data['typeOfMessage'];
convoIndex = $(this).index();
var portId = data['portId'];
if (contactName === null) {
$('#convoTitle').text("Conversation with " + data['sender']);
} else {
$('#convoTitle').text("Conversation with " + data['contactName'] + "(" + data['sender'] + ")");
}
$("#conversationDt").DataTable().ajax.url("getConversation.json?&sender=" + sender + "&portId=" + portId);
$('#conversationDt').DataTable().ajax.reload();
$('#replyMessageDiv').removeClass("hidden");
$('#replyButtonDiv').removeClass("hidden");
});
表数据重新加载:
setInterval(function () {
convoTable.ajax.reload(null, false); // user paging is not reset on reload
if (messageIdTmp !== null) {
if ($('#messageDt tbody > tr:contains(' + messageIdTmp + ')')) {
console.log("EXISTS");
$(this).addClass('isSelected');
}
}
}, 2000);
我也尝试过:
$('#messageDt tbody > tr:contains('+messageIdTmp+')').addClass('isSelected')
当我这样做时:
if (messageIdTmp !== null) {
if ($('#messageDt tbody > tr:contains(' + messageIdTmp + ')')) {
console.log("EXISTS");
$(this).addClass('isSelected');
}
}
或
$('#messageDt tbody > tr:contains('+messageIdTmp+')').addClass('isSelected')
未分配isSelected
类。
即使在isSelected
之后,我仍然需要保留ajax.reload()
类
答案 0 :(得分:1)
我建议:
createdRow
选项在表重绘时重新应用“ selected”类(由.ajax.reload()
引起; 以下代码也演示了这种方法,您可能会在here上找到全面的演示,或者可以使用此link在浏览器中通过Developer Tools进行检查。 :
//global variable that stores selected row id's
const selectedRowIds = [];
//datatable initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
ajax: {
url: '/getdata',
type: 'POST',
dataSrc: ''
},
columns: [{
title: 'id',
data: 'id'
}, {
title: 'item',
data: 'item'
}
],
//re-apply class 'selected' upon table redraw
createdRow: (row, data, dataIndex, cells) => {
if (selectedRowIds.indexOf(data.id) > -1)
$(row).addClass('selected');
}
});
//emulate selection
$('#mytable').on('click', 'td', function () {
//get clicked table row node
const clickedRow = dataTable.row($(this).closest('tr'));
//append/remove selected row 'id' property value to global array
if ($(clickedRow.node()).hasClass('selected')) {
selectedRowIds.splice(selectedRowIds.indexOf(clickedRow.data().id), 1);
console.log(selectedRowIds);
} else {
selectedRowIds.push(clickedRow.data().id);
}
//toggle class 'selected' upon clicking the row
$(clickedRow.node()).toggleClass('selected');
});
//button that triggers '.ajax.reload()'
$('#reload').on('click', () => dataTable.ajax.reload());