【问题标题】:Sorting Table Columns with jQuery Table Sorter使用 jQuery 表格排序器对表格列进行排序
【发布时间】:2010-09-04 06:21:29
【问题描述】:

我想知道是否有办法使用表格排序器对列进行排序
这样我就可以根据一些 ID 或任何东西来排列列。

例如,如果我想对表格进行排序,以便 Apple 列
会是第一个,我该怎么做?

【问题讨论】:

  • 表格排序器没有这个内置的,你绑定到那个插件了吗?还有其他人天生就会这样做,尽管没有我能想到的轻量级。

标签: jquery tablesorter


【解决方案1】:

演示:http://jsfiddle.net/fKMqD/

代码:

var rows = $('tr');

rows.eq(0).find('td').sort(function(a, b){

    return $.text([a]) > $.text([b]) ? 1: -1;

}).each(function(newIndex){

    var originalIndex = $(this).index();

    rows.each(function(){
        var td = $(this).find('td');
        if (originalIndex !== newIndex)
            td.eq(originalIndex).insertAfter(td.eq(newIndex));
    });

});

不需要插件。

【讨论】:

    【解决方案2】:

    有一个名为 datatable 的 jquery 插件,它像大多数插件一样非常易于使用,并且无需任何额外工作即可即时完成您想要的一切。

    http://www.datatables.net/

    检查一下。

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        我就这样搞定了

        <html>
          <head>
            <script type="text/javascript" src="http://www.google.com/jsapi"></script>
            <script type="text/javascript">
              google.load("jquery", "1");
            </script>
            <script>
              $(function() {
                // Figure out the new column order.
                var isWas = {};
                $("tr").eq(0).find("td").each(function(index) {
                  $(this).attr("was", index);
                }).sort(function(left, right) {
                  // Change this line to change how you sort.
                  return $(left).text() > $(right).text() ? 1 : -1;
                }).each(function(index) {
                  isWas[index] = $(this).attr("was");
                });
        
                // Reorder the columns in every row.
                $("tr").each(function() {
                  var tr = $(this);
                  var tds = tr.find("td");
                  var newOrder = [];
                  for (var is = 0; is < tds.length; is++) {
                    newOrder.push(tds.eq(isWas[is]));
                  }
                  for (var is = 0; is < tds.length; is++) {
                    tr.append(newOrder[is]);
                  }
                });
              });
            </script>
          </head>
          <body>
            <table>
              <tr><td>Potato</td><td>Tomato</td><td>Apple</td></tr>
              <tr><td>20g</td><td>10gr</td><td>40gr</td></tr>
            </table>
          </body>
        </html>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-28
          • 2021-12-24
          相关资源
          最近更新 更多