Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

jquery - javascript sort of HTML elements

I'm trying to sort an li elements and get an unexpacted result I need to sort it three times to get it correctly,

where have I mistaken? javascript

var sort_by_name = function(a, b) {
    return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase();
}
$this = $("ol#table1");
var list = $this.children();
list.sort(sort_by_name);
console.log(list);
$this.html(list);

HTML

<ol id="table1" style="display: block; ">
   <li class="menu__run">I</li>
   <li class="menu__run">IXX</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li> 
   <li class="menu__run">IXX</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__run">I</li>
   <li class="menu__test">st</li>
   <li class="menu__test">st</li>
   <li class="menu__test">st</li>
</ol>

fiddle example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are much better ways to sort.

  1. You need a comparison function that returns the right values: -1, 0, and 1.
  2. localeCompare() is such a comparison function.
  3. You can just move the DOM elements around rather than regenerating the HTML.
  4. You can get the LI elements directly in the original selector.
  5. "#table1" is a more efficient selector than "ol#table1".

I would suggest this:

$("div#btn").click(function() {
    var sort_by_name = function(a, b) {
        return a.innerHTML.toLowerCase().localeCompare(b.innerHTML.toLowerCase());
    }

    var list = $("#table1 > li").get();
    list.sort(sort_by_name);
    for (var i = 0; i < list.length; i++) {
        list[i].parentNode.appendChild(list[i]);
    }
});?

Which you can see work here: http://jsfiddle.net/jfriend00/yqd3w/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...