如何在jQuery中使用自定义排序顺序对列表项进行排序 [英] How to sort list items using custom sort order in jQuery
问题描述
我的问题与我在Stack Overflow上发现的其他问题非常相似,但并不完全相同.
My question is very similar to a number of others I've found on Stack Overflow, but not quite the same.
我想基于每个项目中包含的跨度的内容对列表项进行排序-但要使用我可以定义的排序顺序.这是示例列表项的HTML:
I'd like to sort list items based on the content of a span contained within each item -- but using a sort order that I can define. Here's the HTML for a sample list item:
<li>
<span class="fname">John</span>
<span class="lname">Doe</span>
<span class="year">Sophomore</span>
</li>
我想基于年份"跨度的内容进行排序,但是要按时间顺序而不是按字母顺序进行排序.显然,顺序是:
I want to sort based on the content of the "year" span, but chronologically rather than alphabetically. The order, obviously, needs to be:
- 新鲜人
- 二年级学生
- 初中
- 高级
我该怎么做?
仅供参考,我正在使用以下jQuery代码(效果很好)按姓氏按字母顺序排序:
Just for reference, I'm using the following jQuery code (which works perfectly) to sort alphabetically by last name:
function sortByLastName(){
var myList = $('#foo ul');
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
var compA = $(a).find('.lname').text().toUpperCase();
var compB = $(b).find('.lname').text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$(myList).append(listItems);
};
推荐答案
要匹配您的sortByLastName()函数,这将起作用:
To match your sortByLastName() function, this would work:
function sortByYear(){
var myYears = ['Freshman', 'Sophomore', 'Junior', 'Senior'];
var myList = $('#foo ul');
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
var compA = $.inArray($(a).find('.year').text(), myYears);
var compB = $.inArray($(b).find('.year').text(), myYears);
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$(myList).append(listItems);
}
只需使用 $ .inArray()即可找到大批.请注意,对于数组中未找到的值,这将返回-1,这会将这些元素放在列表的顶部.
Just use $.inArray() to find the indices of each school year within the array. Note that this will return -1 for values not found in the array, which will put those elements at the top of your list.
这篇关于如何在jQuery中使用自定义排序顺序对列表项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!