Javascript/JQuery 按字母顺序对带有锚点的列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13394796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:38:20 来源:igfitidea点击:
Javascript/JQuery to sort alphabetically a list with anchors
提问by MIlena
I have this list:
我有这个清单:
<ul id="demoOne" class="demo">
<li><a href='http://site/Service.aspx?shId=1154'>Dhenie fotokopje aktesh nga dosja 12</a></li>
<li><a href='http://site/Service.aspx?shId=1155'>Depozitim kerkesash Ankimore/Rekurse
kunder vendimeve civile/penale 12</a></li>
<li><a href='http://site/Service.aspx?shId=1156'>Dhenie Vendimesh12</a></li>
<li><a href='http://site/Service.aspx?shId=1157'>Integrimi i Ish te Perndjekurve Polikite
12</a> </li>
<li><a href='http://site/Service.aspx?shId=1158'>Dhenie Drejtesie</a></li>
<li><a href='http://site/Service.aspx?shId=1159'>Gjykata e Rrethit Gjyq?sor Lezh? ushtron
juridiksionin gjyq?sor civil dhe penal n? territorin e qarkut Lezh? t? Republik?s
s? Shqip?ris?.</a></li>
</ul>
I want to alphabetically sort this list, using the anchor text, not the li text. How to do that?
我想使用锚文本而不是 li 文本按字母顺序对这个列表进行排序。怎么做?
I'm using this script to sort them by li text
我正在使用此脚本按 li 文本对它们进行排序
function sortUnorderedList(ul, sortDescending) {
var items = $('.demo li').get();
items.sort(function(a,b){
var keyA = $(a).text();
var keyB = $(b).text();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
var keyA = $(a).text();
var keyB = $(b).text();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
var ul = $('.demo');
$.each(items, function(i, li){
ul.append(li);
});
}
回答by Jai
try this:
试试这个:
$(function() {
$.fn.sortList = function() {
var mylist = $(this);
var listitems = $('li', mylist).get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : 1;
});
$.each(listitems, function(i, itm) {
mylist.append(itm);
});
}
$("ul#demoOne").sortList();
});
回答by undefined
You can use sort
method.
您可以使用sort
方法。
$('#demoOne li').sort(function(a, b){
return $('a', a).text() > $('a', b).text()
}).appendTo('#demoOne');