【问题标题】:HTML table rows custom sort using jQuery使用jQuery的HTML表格行自定义排序
【发布时间】:2014-03-18 19:01:08
【问题描述】:

我正在对Code/SKU 列上的表格行进行排序。 Code/SKU 列可能包含也可能不包含-(破折号),这是我的分隔符。 - 之后的 3 位代码是我的产品机架号,前缀介于 A-Z 之间。我正在尝试根据机架号irrespective of the prefix 对产品进行升序排序。如果机架号缺失,这些产品应列在顶部。

例如,如果 输入 Code/SKU 列包含:

RIN65631-A24
PNT64705
CPC31378-D06

那么输出Code/SKU column应该排序为:

PNT64705
CPC31378-D06
RIN65631-A24

这是我的JSFiddle

如上所述,我得到了所需的输出,但是如果您查看我的 JSFiddle,您会发现我正在使用多个调用 $(this).find() 函数从 DOM 中检索一个特定的元素,而 IMO 是不必要的。可能有更好的方法来避免冗余的 find() 调用并实现相同的输出。有人可以在这方面帮助我吗?

编辑:

注意:排序应该在 DOM 就绪事件上进行。

【问题讨论】:

  • 你有没有想过使用像datatables.net 这样的东西来做你的排序?您还可以拦截该特定列上的排序事件并执行不同的操作。
  • @Moby'sStuntDouble 感谢您的建议,但 datatables.net 插件将根据 Code/SKU 的“字母数字”值对元素进行排序,而要求是对 just the numeric part 的自定义排序代码/SKU 中的机架号。

标签: jquery html sorting html-table


【解决方案1】:

使用sortContentjquery 插件:

 $('td.sku').sortContent({asc:true,
                         target:function(e){
                           return $(e).parent();
                         },helper:function(e){
                            var html=$(e).html().split('-'); 
                            if(html.length===2){return html[1]}
                             else {return ''}    
                          }
 });

Demo

说明

  • target callbak:你按照td元素排序,但是tr应该是排序的。所以目标是tr,它是td元素的父元素。

  • helper:识别要排序的内容

更新:

仅对数字字符进行排序,Helper 回调应如下所示:

var myhelper=function(e){
   var html=$(e).html().split('-'); 
    if(html.length===2){return 'b'+html[1].numeric()}
    else {return 'a'+html[0].numeric()}

};

Demo v2

【讨论】:

  • 首先,我不希望页面上的任何“排序 IT”按钮触发排序。数据已经加载到 DOM 中,这就是我想使用 jQuery 排序的数据。
  • 其次,您的排序功能不会产生所需的输出。它在我的机架号的“字母数字”值上对元素进行排序,而要求是在 just the numeric part of that rack number 上排序。请检查我在问题中的输入和输出。
  • 这正是我想要的。赞赏!!
【解决方案2】:
$(document).ready(function(){
var th = jQuery('.shortid'),
    inverse = false;

th.click(function(){

    var header = $(this),
        index = header.index();

    header
        .closest('.right-contacts-details')
        .find('.shorting')
        .filter(function(){
            return $(this).index() === index;
        })
        .sort(function(a, b){

            a = $(a).text();
            b = $(b).text();

            return (
                isNaN(a) || isNaN(b) ?
                    a > b : +a > +b
                ) ?
                    inverse ? -1 : 1 :
                    inverse ? 1 : -1;

        }, function(){
            return this.parentNode;
        });

    inverse = !inverse;

});

});

【讨论】:

    【解决方案3】:

    使用 KnockoutJS。您可以立即使用该功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 2021-08-04
      • 2014-01-05
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多