如何在jQuery中按值对子进行排序 [英] How to sort children by value in jQuery
本文介绍了如何在jQuery中按值对子进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有与我想要排序的跨度值的链接。
I have links with span values that I want to sort by.
在这个例子中,我想按金额排序。
In this example I want to sort by amount.
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')')
怎么了?为什么我不能将金额的值添加到排序数组?
What's wrong? Why can't I add the value of the amount to the sorted array?
推荐答案
如果您需要对列表进行排序我认为如果你使用一些jQuery功能可以简单得多:
If you need to sort a list I think it can be much simpler if you use some of the jQuery power:
$('#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/
我做了 a
阻止CSS以方便摆脱< br>
标记。
Demo: http://jsfiddle.net/rF7LR/2/
I made a
block with CSS for convenience to get rid of <br>
tags.
这篇关于如何在jQuery中按值对子进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文