【问题标题】:jQuery sort table row by the value of one tdjQuery 按一个 td 的值对表格行进行排序
【发布时间】:2015-03-20 22:24:44
【问题描述】:

你会如何按照我拥有的pts 类对该表进行排序:

<table>
    <tr>
        <th>rank</th>
        <th>team</th>
        <th>pts</th>
    </tr>
    <tr>
        <td>1.</td>
        <td>Chelsea</td>
        <td class="pts">3</td>
    </tr>
    <tr>
        <td>2.</td>
        <td>Arsenal</td>
        <td class="pts">1</td>
    </tr>
    <tr>
        <td>3.</td>
        <td>Man U</td>
        <td class="pts">2</td>
    </tr>
</table>

<button>SORT</button>

代码: http://jsfiddle.net/dxL8b2k0/

【问题讨论】:

  • ids 在文档中应该是唯一的。你在复制id="pts"
  • 你说的对,我已经改成class了,你知道怎么做吗?
  • 别忘了使用&lt;thead&gt;&lt;tbody&gt; 元素。看起来你在下面得到了一个很好的排序答案。

标签: jquery


【解决方案1】:

为了有一个有效的表,你应该用thead 元素包装第一个tr,用tbody 元素包装其他trs。要对trs 进行排序,您可以使用sort 方法:

$('tbody > tr').sort(function (a, b) {
    return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody');

要更新排名单元格,您可以使用text 方法:

$('tbody > tr').sort(function (a, b) {
    return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody').find('td:first').text(function(index) {
    return ++index + '.';
});

【讨论】:

  • localeCompare的支持不是很好,也许只是return $('td.pts', a).text() - $('td.pts', b).text()
  • 编辑后,由于您有字符串,它将无法正常工作。它将评估第一个字符,即'12' &lt; '3' === true。您需要像 +$('td.pts', b).text() &gt; +$('td.pts', a).text(); 一样解析它
  • @Karl-AndréGagnon 是的,完全正确。感谢您提及!
  • 你如何让排名数字按顺序保持粘性?
  • @PirateApp 该过程由浏览器的 DOM 引擎在幕后进行。
【解决方案2】:

查看此更新的fiddle 以获取工作版本:

$('#btnGo').on('click', function () {
    // get rows as array and detach them from the table
    var rows = $('#tbl tr:not(:first)').detach();

    // sort rows by the number in the td with class "pts"
    rows.sort(function (row1, row2) {
        return parseInt($(row1).find('td.pts').text()) - parseInt($(row2).find('td.pts').text());
    });

    // add each row back to the table in the sorted order (and update the rank)
    var rank = 1;
    rows.each(function () {
        $(this).find('td:first').text(rank + '.');
        rank++;
        $(this).appendTo('#tbl');
    });
});

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多