jQuery DataTables:如何添加类if the string exists in the?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery DataTables:如何添加类if the string exists in the?相关的知识,希望对你有一定的参考价值。

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

我创建了一个代码,当用户点击<tr>时,背景颜色会发生变化。然后将行的ID存储到变量中。重新加载DataTable后,我使用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);

行'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");

});

表数据重新加载:

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()级别

答案

我建议:

  • 具有存储所选行id的全局变量;
  • 使用createdRow选项在表重绘时重新应用'selected'类(由.ajax.reload()引起;
  • 以及操纵'selected'类将所选行id推入/移出全局数组;

以下代码演示了这种方法,您也可以在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());

以上是关于jQuery DataTables:如何添加类if the string exists in the?的主要内容,如果未能解决你的问题,请参考以下文章

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

jQuery Datatables 突出显示行

如何在 jQuery DataTables 中添加静态列

dataTables jquery - 如何添加排序图像/图标?

如何在 jQuery dataTables 列中添加一些信息

如何删除 jQuery DataTables 插件添加的搜索栏和页脚?