jQuery DataTables:如果 <td> 中存在字符串,如何将 class 添加到 <tr>?

jQuery DataTables: How to add a class to <tr> if the string exists in the <td>?

我正在使用 jQuery 数据 Table 来显示我需要的数据。 table 的行将根据数据而变化。当用户单击该行时,该行将被选中。我的 table 使用 ajax.reload() 重新加载。问题是当 table 重新加载时,所选行被取消选择。

我创建了一个代码,当用户点击 <tr> 时,背景颜色会改变。然后将行的 ID 存储到一个变量中。重新加载数据Table后,我使用contains()检查ID是否存在于table中,然后尝试添加表明它被选中的class。

我的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>

数据Table初始化代码:

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);

行 'click' 处理程序:

$('#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");

});

Table 数据重新加载:

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 class 未分配。

即使在 ajax.reload()

之后,我也需要保留 isSelected class

我建议:

  • 具有存储选定行 ID 的全局变量;
  • 使用 createdRow 选项在 table 重绘时重新应用 'selected' class(由 .ajax.reload();
  • 连同操纵'selected'classpush/drop选择的行idto/from全局数组;

以下代码演示了该方法,此外,您可能会在 here, or you may examine that with Developer Tools in your browser using this 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());