【问题标题】:sorting the columns of html table对html表的列进行排序
【发布时间】:2014-09-19 05:49:28
【问题描述】:

我在 this fiddle 中有一个 html 表,并尝试使用 jquery 参考 this stack overflow answer 对列进行排序,

var arr = $('th').filter(function() {
   return (new Date(this.innerHTML)).getDate();
}).sort(function (a, b) {
    return new Date(a.innerHTML) > new Date(b.innerHTML);
}).map(function () {
    return this.cellIndex
}).get();

$('tr').each(function () {
    $(this).children().filter(function(){
       return $.inArray(this.cellIndex, arr)> -1;
    }).sort(function (a, b) {
        a = $.inArray(a.cellIndex, arr);
        b = $.inArray(b.cellIndex, arr);
        return a > b;
    }).insertBefore(this.lastElementChild);
});

它可以正常工作长达 10 个月的列。但如果月份列数超过 10,排序将崩溃,如小提琴中给出的。我该如何解决这个问题?

【问题讨论】:

  • 不确定这可能如何工作。返回的日期都是无效的。可以通过将它们记录到您的排序或过滤器中的控制台来进行验证。试试console.log(new Date('Feb 2014')) 作为证据
  • 我想按月份排序。我提到了this stack answer中给出的这个小提琴jsfiddle.net/AEvpd
  • 定义按月、年排序不重要?据我所见,演示不起作用。还有你拥有的非日期列呢?
  • 小提琴 jsfiddle.net/AEvpd 在 chrome 中工作正常
  • 好的,我没有检查 chrome,并提出了基于 Firefox 不接受缩写日期的问题。

标签: jquery sorting html-table


【解决方案1】:

如果您打印数组arr 中的条目,您会发现排序错误。这与排序功能有关。

给定输入(a, b),原始代码中的排序函数返回a > b。在a <= b的情况下,排序函数会返回0,所以如果我们有严格的不等式a < b,排序函数会建议ab一样大(因为它返回0),这就是出现错误的地方。

你可以试试下面的代码:

DEMO

var arr = $('th').filter(function() {
   return (new Date(this.innerHTML)).getDate();
}).sort(function (a, b) {
    aDate = new Date(a.innerHTML);
    bDate = new Date(b.innerHTML);
    if (aDate > bDate) {
        return 1;
    } else if (aDate < bDate) {
        return -1;
    } else {
        return 0;
    }
}).map(function () {
    return this.cellIndex
}).get();

$('tr').each(function () {
    $(this).children().filter(function(){
       return $.inArray(this.cellIndex, arr)> -1;
    }).sort(function (a, b) {
        a = $.inArray(a.cellIndex, arr);
        b = $.inArray(b.cellIndex, arr);
        if (a > b) {
            return 1;
        } else if (a < b) {
            return -1;
        } else {
            return 0;
        }
    }).insertBefore(this.lastElementChild);
});

【讨论】:

  • 我想按月份排序。我在this stack answer中提到了这个小提琴jsfiddle.net/AEvpd
  • 年份在排序中是否重要? Oct 2013 是在 Jun 2014 之后出现的吗?
  • 是的。月份和年份。就像在小提琴jsfiddle.net/AEvpd 中一样。 Oct 2013 应该在 Jun 2014 之前
  • 你查看过我发的DEMO了吗?如果是这样,它有什么问题?
  • 我添加了一个日期 01 以使其与 mozilla jsfiddle.net/AEvpd/3 一起使用
猜你喜欢
  • 2017-10-04
  • 2015-04-01
  • 1970-01-01
  • 2012-10-10
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多