简体   繁体   中英

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.

How can I do that?

Thanks

hope this article will help u perfectly

http://james.padolsey.com/javascript/sorting-elements-with-jquery/

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

$('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:

var liArray = [];

$(".t-header li").each(function(){
    liArray.push($(this).html());
});

//sort them (alphabetically):
liArray.sort();

fiddle here: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM