触发Tablesorter以在条目插入表时保持排序

问题描述 投票:1回答:1

我有一个使用表分类器的表,虽然排序工作正常,但是当表变得乱序时我遇到了一个案例。也就是说,当一个条目添加到表中时,不再对该表进行排序。如何使用单击处理程序触发表分类器以维持其当前的排序状态(即,升序,降序)。

目前,我正在编写自己的排序算法来处理这种特殊情况,但如果存在表分类器解决方案,似乎可能会浪费精力。

addEntry.click(function() {
    // code that triggers the sort again
});
javascript jquery tablesorter
1个回答
2
投票

初始化窗口小部件时可以使用sortlist属性,并在添加新行后触发addRows

在任何情况下,您始终可以在表标题上触发需要排序的列的单击事件。

片段:

//
// set sort on first column in descending order and 
// on second column in ascending order
//
$("#myTable").tablesorter({ sortList: [[0,1], [1,0]] });
$('#addNewRow').on('click', function(e) {
    var newRow = $('<tr><td>z</td><td>a</td></tr>');
    $("#myTable tbody").append(newRow).trigger('addRows', [newRow, true]);
});

$('#sortOnFirstCol').on('click', function(e) {
    $("#myTable th:first").trigger('click');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/css/theme.default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.min.js"></script>

<button id="addNewRow">Add new Row</button>
<button id="sortOnFirstCol">Sort on first column</button>
<table id="myTable" class="tablesorter">
    <thead>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Smith</td>
        <td>John</td>
    </tr>
    <tr>
        <td>Bach</td>
        <td>Frank</td>
    </tr>
    <tr>
        <td>Doe</td>
        <td>Jason</td>
    </tr>
    <tr>
        <td>Conway</td>
        <td>Tim</td>
    </tr>
    </tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.