[英]How to select li elements of an ul in jquery?
I have an unordered list: 我有一个无序列表:
<li class="t-header" id = "BackLogList">
<ul>
<li class="t-header-description">Description</li>
<li class="t-header-project-name">Project Name</li>
<li class="t-header-Type">Type</li>
<li class="t-header-priority">Priority</li>
<li class="t-header-status">Status</li>
</ul>
</li>
I need to select the html texts of all the li elements and sort them using jquery. 我需要选择所有li元素的html文本,并使用jquery对它们进行排序。
How can I do that? 我怎样才能做到这一点?
Thanks 谢谢
hope this article will help u perfectly 希望本文能对您有所帮助
Happy to Help :) 很高兴为您提供帮助 :)
您可以尝试以下简单代码:
$('#BackLogList li').sort(function(a,b){return a.innerHTML > b.innerHTML ? 1 : -1;}).appendTo('#BackLogList ul');
If thats your whole list I would change the markup to: 如果那是您的整个列表,则可以将标记更改为:
<ul id="BacklogList">
<li class="t-header-description">Description</li>
<li class="t-header-project-name">Project Name</li>
<li class="t-header-Type">Type</li>
<li class="t-header-priority">Priority</li>
<li class="t-header-status">Status</li>
</ul>
u can get li array like this 你可以像这样得到li数组
$('ul').children('li')
and u can get their text's like this 你可以得到他们的文字是这样的
$('ul').children('li').each(function(){
alert($(this).text())
})
and about sorting how u want the sort them? 以及有关如何排序的信息?
Are you looking for something like this? 您是否正在寻找这样的东西?
$( '.t-header li' ).each( function() {
//Search algorithm where $( this ) is the current li that is handled
} );
pick the html of each and place them into an array: 选择每个的html并将它们放入数组中:
var liArray = [];
$(".t-header li").each(function(){
liArray.push($(this).html());
});
//sort them (alphabetically):
liArray.sort();
fiddle here: http://jsfiddle.net/v5XB9/ 在这里提琴: http : //jsfiddle.net/v5XB9/
例如:
var items = $("ul li").map(function(){return $(this).text();}).get().sort();
var ul = $('#BackLogList');
var lis = ul.children('li').get();
lis.sort(function(a,b){
var v1 = $(a).text(),v2 = $(b).text();
if(v1 === v2)
return 0;
return v1 < v2 ? 1 : -1;
});
ul.html(lis);
Get the texts as array to get them sortable as you wish. 将文本作为数组获取,以根据需要对其进行排序。
lis = $('#BackLogList li');
text = $.map(lis, function(value, index) {
return $(value).text();
});
//"text" is now an array of texts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.