Sort Unordered List with Javascript

后端 未结 1 1691
滥情空心
滥情空心 2021-01-23 10:40

I have been looking at the stackoverflow thread:

How may I sort a list alphabetically using jQuery?

but for my scenario, I have the hierachy:

<         


        
相关标签:
1条回答
  • 2021-01-23 11:09

    I would recommend using a jQuery-based solution for this, because once you start getting into multiple DOM levels (e.g. sorting siblings at one level based on the contents of elements at a deeper level) the simple sort mechanism breaks down. It's an extremely rough solution - essentially blowing away the existing HTML and replacing it in raw text mode with other HTML. We can do better by actually shuffling the DOM elements around:

    function sort(list, key) {
        $($(list).get().reverse()).each(function(outer) {
            var sorting = this;
            $($(list).get().reverse()).each(function(inner) {
                if($(key, this).text().localeCompare($(key, sorting).text()) > 0) {
                    this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
                }
            });
        });
    }
    

    To use it, we pass in a selector to the list and a selector to use to locate the key we want to sort on:

    <ul class="toBeSorted">
        <li><a href="...">sort me</a></li>
    </ul>
    
    <script type="text/javascript">
        sort('ul.toBeSorted>li', 'a');
    
        //we want to sort the <li>'s in ul.toBeSorted;
        //and we want to use the text of the first and only <a>
        //in each item as the sort key
    </script>
    
    0 讨论(0)
提交回复
热议问题