javascript 在选择框更改时按升序和降序对 HTML 表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20856357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:28:06  来源:igfitidea点击:

Sort HTML table in ascending and descending order on select box change

javascriptjqueryhtmltablesorter

提问by Hammad

I want to sort the data in my table in ascending and descending order on select box change. If user selects Ascending from select box option then the data should be sorted in ascending order and same goes for the descending order. I know this is pretty simple but I am a total newbie so please help me do this. This is what I have done so far.

我想在选择框更改时按升序和降序对表中的数据进行排序。如果用户从选择框选项中选择升序,则数据应按升序排序,降序也是如此。我知道这很简单,但我是个新手,所以请帮我做这件事。这是我迄今为止所做的。

FIDDLE

小提琴

function createClickHandler(column, isAscending){
    return function(e){
      table.find('td')
        .filter(function(){
          return $(this).index() === column;
        })
        .sort(function(a, b){
          var order = $.text([a]) > $.text([b]);
          return isAscending ? order : !order;
        }, function(){
          // parentNode is the element we want to move
          return this.parentNode; 
        })
      ;
    };
  }

Thanks in advance

提前致谢

回答by rrugbys

There are various plugins to perform this using jQuery. The most known one is jQuery tablesorter: Try this, it works for me http://tablesorter.com/docs/#Demo

有各种插件可以使用 jQuery 执行此操作。最著名的是 jQuery tablesorter:试试这个,它对我 有用 http://tablesorter.com/docs/#Demo

$("#myTable").tablesorter(); use this on change event of your select box

$("#myTable").tablesorter(); 在选择框的更改事件上使用它

Check this on fiddle:http://bit.ly/1cEApUh

在小提琴上检查这个:http: //bit.ly/1cEApUh

sorting = [[0,0]];

排序 = [[0,0]];

This is the array that defines those attribute

这是定义这些属性的数组

In first field you need to add the column index. in my case the column index is 0. If you change it for 1, it will sort according to year

在第一个字段中,您需要添加列索引。在我的情况下,列索引为 0。如果将其更改为 1,它将按年份排序

And the second field contains either 0 and 1, 0 for ascending and 1 for ascending

第二个字段包含 0 和 1,0 表示升序,1 表示升序

Let us take an example for sorting make column

让我们举个例子对 make 列进行排序

if($(this).val() === "Ascending") sorting = [[2,0]]; else sorting = [[2,1]];

if($(this).val() === "升序") 排序 = [[2,0]]; 否则排序 = [[2,1]];