使用jquery对自定义数据表进行升序和降序排序

时间:2012-03-02 14:31:44

标签: javascript jquery html jquery-ui

我有以下数据表,单独排序升序和降序按钮。 我正在使用jQuery插件“jQuery.fn.sort”James Padolsey

这是工作示例

http://jsbin.com/alawub/2/edit

enter image description here

我想为每个Col添加排序但是它不起作用请查看我的JS代码以上任何其他替代解决方案,欢迎这样做。

5 个答案:

答案 0 :(得分:5)

您要多次添加点击处理程序:

$('th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){
        ...
        $('#accending_1,#accending_2').click(function(e){

这将是每个th,并且有两行第4个标签,为id为accending_1和accending_2的元素添加一个点击处理程序。这将为每个按钮添加8个点击处理程序!

有很多方法可以解决这个问题。不是每个按钮都有特定的id,而是使用类并相对于标题找到它们:

$('th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){

        $('.accending', this).click(

example

注意最后一行的this参数将选择器限制为当前TH的后代。那仍然会搜索TH的顶行。

最好直接搜索按钮然后找出它们所在的列。

  $('.accending, .accending')
    .wrapInner('<span title="sort this column"/>')
    .click(function(e){
      console.log("click");
      var th = $(this).closest('th'),
        thIndex = th.index();
      table.find('td')
        .filter(function(){
          return $(this).index() === thIndex;
        })
        .sort(
          function(a, b){
            return $.text([a]) > $.text([b]);
          }, function(){
            // parentNode is the element we want to move
            return this.parentNode; 
          }
        );
    });
  $('.decending, .decending')

example

代码中仍然有很多重复,而且html。

加入和降序点击处理程序几乎相同,所以我们只需要传递sort函数。

  //This function returns another function which is a click handler. 
  //It takes the sort function as a parameter.
  function createClickHandler(sortFunction){
    return function(e){
      var th = $(e.target).closest('th'),
        thIndex = th.index();
      console.log(th);
      table.find('td')
        .filter(function(){
          return $(this).index() === thIndex;
        })
        .sort(sortFunction, function(){
            // parentNode is the element we want to move
            return this.parentNode; 
          }
        );
    };
  }

  $('.accending, .accending')
    .wrapInner('<span title="sort this column"/>')
    .click(createClickHandler(function(a, b){
        return $.text([a]) > $.text([b]);
      })
    );
  $('.decending, .decending')
    .wrapInner('<span title="sort this column"/>')
    .click(createClickHandler(function(a, b){
        return $.text([a]) < $.text([b]);
      })
    );

example

HTML也可以稍微清理一下。按钮的标签都是相同的,所以我们可以直接从javascript添加点击处理程序,而不必搜索它们。由于我们再次遍历列标题,我们可以清理如何获取列号。最后,传递两个不同的排序函数有点浪费,所以让我们传递一个方向参数。

  //This function returns another function which is a click handler. 
  //It takes the sort function as a parameter.
  function createClickHandler(column, isAccending){
    return function(e){
      table.find('td')
        .filter(function(){
          return $(this).index() === column;
        })
        .sort(function(a, b){
          var order = $.text([a]) > $.text([b]);
          return isAccending ? order : !order;
        }, function(){
          // parentNode is the element we want to move
          return this.parentNode; 
        })
      ;
    };
  }

  $('#controls th').each(function(column,item){
    //Note we get the column index for for free with the each function
    $(this)
      .append($('<a title="sort this column" href="#">Ascending</a>')
        .click(createClickHandler(column, true))
      )
      .append('&nbsp;&nbsp;')
      .append($('<a title="sort this column" href="#">Decending</a>')
        .click(createClickHandler(column, false))
      )
      ;
  });

example


请注意,我删除了逆变量。它从未被使用过。

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

我不确定你认为这是怎么回事,但由于automatic semicolon insertion,它实际上是在第一行返回。它将被解释为:

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

所以逆是死代码。这是javascript的坏点之一,并不是很明显。 jsbin警告你丢失分号。在此处提交代码之前,总是值得修复任何错误/警告。

答案 1 :(得分:0)

我非常喜欢kryogenix.org上的“sorttable”脚本 - http://www.kryogenix.org/code/browser/sorttable/

非常易于使用和设置。

答案 2 :(得分:0)

我让你的代码工作了。这是代码,你也可以在jsbin中测试它:http://jsbin.com/alawub/15/

使用Javascript:

$(document).ready(function(){

  var $table = $('table');
  $table.on('click', 'th a.accending_1, th a.decending_1', function(e){
    var th = $(e.target).parent('th'),
    thIndex = th.index(),
    direction = $(e.target).attr('class').match('accending')?'A':'D', 
    sortDir = th.data('direction'+thIndex);
    if(sortDir  && sortDir == direction ) return;

      $table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sort(function(a, b){
                if( direction == 'D' )
                   return $.text([a]) > $.text([b]) ? -1 : 1;
                else 
                   return $.text([a]) > $.text([b]) ? 1 : -1;

            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
         th.data('direction'+thIndex, direction);
    });

});

HTML :(刚修正的A类)

    <th id="facility_header1">
        Table Header 1<br />
        <a href="#" class="accending_1">Accending</a>&nbsp;&nbsp;
        <a href="#" class="decending_1">Decending</a>
    </th>
     <th id="facility_header2">
        Table Header 2<br />
        <a href="#" class="accending_1">Accending</a>&nbsp;&nbsp;
        <a href="#" class="decending_1">Decending</a>
  </th>

jsbin上的工作示例:http://jsbin.com/alawub/15/

答案 3 :(得分:0)

我认为tablesorter提供了您需要的功能。它当然处理文本和数字列。动态更新表格存在问题,但有一个很好的修复here

答案 4 :(得分:0)

我可以在JS Bin看到4个警告。

第67行:返回$ .text([a])&gt; $ .text([b])---缺少分号。
第68行:逆? -1:1 ---期望一个赋值或函数调用,而是看到一个表达式 第82行:返回$ .text([a])&lt; $ .text([b])---缺少分号。
第83行:逆? 1:-1; ---期望一个赋值或函数调用,而是看到一个表达式。

希望纠正这些错误会给你预期的结果。

相关问题