这个Javascript多字段排序有什么问题?

时间:2015-07-06 10:25:29

标签: javascript jquery

This是我的代码:

<div class="item" data-count="1" data-title="C">1 C</div>
<div class="item" data-count="2" data-title="D">2 D</div>
<div class="item" data-count="2" data-title="A">2 A</div>
<div class="item" data-count="1" data-title="Z">1 Z</div>

$('.item').sort(function (x, y) {
    var n = $(x).attr("data-count") - $(y).attr("data-count");
    if (n != 0) {
        return n;
    }

    return $(x).attr("data-title") - $(y).attr("data-title");
});

我想首先为.item降级data-count订购data-title,然后为2 A 2 D 1 C 1 Z 升序订购。

即。结果必须是:

1 C
2 D
2 A
1 Z

而是:

Db.Products
.Where(p=>string.IsNullOrEmty(colorTexBox.Text) || p.color==colorTexBox.Text)
.Where(p=>check other property...)
.
.
.AsEnumerable()     

我对这个排序功能错了吗?

2 个答案:

答案 0 :(得分:2)

尝试使用此排序功能。它对我有用。

HTML。

<div class="testWrapper">
    <div class="item" data-count="1" data-title="C">1 C</div>
    <div class="item" data-count="2" data-title="D">2 D</div>
    <div class="item" data-count="2" data-title="A">2 A</div>
    <div class="item" data-count="1" data-title="Z">1 Z</div>
</div>

的Javascript。

var $wrapper = $('.testWrapper');

$wrapper.find('.item').sort(function (a, b) {
    return +b.getAttribute('data-count') - +a.getAttribute('data-count') ||  a.getAttribute('data-title') > b.getAttribute('data-title');
})
.appendTo( $wrapper );

检查我的例子。 https://jsfiddle.net/88k8kbsz/

答案 1 :(得分:0)

我们可以解决三个主要问题:

  • 要比较计数,我们应该使用parseInt来比较整数而不是字符串。
  • 要比较字符串,我们应该使用localeCompare来获取0,1或-1而不是减去字符串。
  • 在对元素数组进行排序之后,我们需要用已排序的元素替换现有元素。

以下是显示如何执行上述操作的JSFiddle

function parse(node) {
    return {
        // Parse integer from attribute
        count: parseInt($(node).attr("data-count"), 10),
        title: $(node).attr("data-title")
    };
}

var items = $('.item').toArray().sort(function (x, y) {
    var xData = parse(x);
    var yData = parse(y);
    if (xData.count !== yData.count) {
        return xData.count - yData.count;
    }

    // Compare strings
    return xData.title.localeCompare(yData.title);
});

// Replace existing children with sorted children
$('.container').empty();
$('.container').append(items);