如何在jQuery中按值对子进行排序

时间:2014-03-31 09:22:13

标签: javascript jquery

我有与我想要排序的跨度值的链接。

http://jsfiddle.net/rF7LR/

在这个例子中,我想按金额排序。

HTML:

<a id = "sortamount" class = "sort"><span>amount</span></a>

<div id='entrytable'> 
    <a class="entrylink" href="/link">

                <span class = "entry amount">10</span>

                <span class = "entry rating">11</span>

                <span class = "entry price">12</span>

            </a><br>
      <a class="entrylink" href="/link">

                <span class = "entry amount">15</span>

                <span class = "entry rating">16</span>

                <span class = "entry price">100</span>

            </a><br>
     <a class="entrylink" href="/link">

                <span class = "entry amount">13</span>

                <span class = "entry rating">12</span>

                <span class = "entry price">11</span>

            </a><br>

</div>

JS:

$('#sortamount').on('click', function() {
    var entries = document.getElementsByClassName('entrylink'); //nodelist
    var sorted = [];

    for (var i = 0; i < entries.length; i++) { 
        var value = entries[i].children('span.amount').val();
        sorted.push(value);
    }

    sorted.sort();
    $('#entrytable').html('');

    for (var i = 0; i < entries.length; i++) { 
        //find entrylink with sorted amount
        entries.filter(function(){return this.children('a span.amount').val() == sorted[i]});
        //append to entrytable
    }
});

现在我在

收到错误
var value = entries[i].children('span.amount').val();

'[object HTMLCollection]' is not a function (evaluating 'entries[i].children('span.amount')')

怎么了?为什么我不能将金额的值添加到排序数组?

2 个答案:

答案 0 :(得分:3)

如果你需要对列表进行排序,我认为如果你使用一些jQuery功能可以简单得多:

$('#sortamount').on('click', function () {
    $('.entrylink').sort(function(a, b) {
        return $(a).find('.amount').text() - $(b).find('.amount').text();
    })
    .appendTo('#entrytable');
});

演示:http://jsfiddle.net/rF7LR/2/

我使用CSS制作了a块,以方便摆脱<br>标签。

答案 1 :(得分:2)

这样做:

var value = $(entries[i]).children('span.amount').val();

现在你要包装要用于jquery方法的entries[i]