jQuery DataTables:如果字符串存在于 <td> 中,如何将类添加到 <tr>?
Posted
技术标签:
【中文标题】jQuery DataTables:如果字符串存在于 <td> 中,如何将类添加到 <tr>?【英文标题】:jQuery DataTables: How to add a class to <tr> if the string exists in the <td>? 【发布时间】:2019-08-31 14:21:11 【问题描述】:我正在使用 jQuery DataTables 来显示我需要的数据。表格的行将根据数据而变化。当用户单击该行时,该行将被选中。我的表使用ajax.reload()
重新加载。问题是当重新加载表时,选定的行会被取消选择。
我创建了一个代码,当用户点击<tr>
时,背景颜色会发生变化。然后将行的 ID 存储到一个变量中。重新加载 DataTable 后,我使用contains()
检查表中是否存在 ID,然后尝试添加指示它被选中的类。
我的 html:
<table id="messageDt" class="table table-no-bordered table-hover display" cellspacing="0" 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
类未分配。
即使在ajax.reload()
之后,我也需要保留isSelected
课程
【问题讨论】:
【参考方案1】:我建议:
具有存储选定行 ID 的全局变量; 使用createdRow
选项在表格重绘时重新应用“选定”类(由.ajax.reload()
引起;
连同操作“选定”类将选定的行 ID 推入/删除全局数组;
以下代码演示了该方法,此外,您可能会在here 上找到完整演示,或者您可以使用浏览器中的开发者工具使用此link 进行检查:
//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());
【讨论】:
我忘记了createdRow:()
,尽管我正在使用它。感谢@Sneaky Bastard 的帮助
@PatrickBrianGarcia:不客气。如果它解决了您的问题,您可以接受答案。以上是关于jQuery DataTables:如果字符串存在于 <td> 中,如何将类添加到 <tr>?的主要内容,如果未能解决你的问题,请参考以下文章
jQuery DataTables插件 aoColumnDefs跟aoColumns的用法