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
178 views
in Technique[技术] by (71.8m points)

javascript - UL and LI with jQuery 3.2.1 running error

I have this working link where it is displaied the outcome I want

However when I insert my code to Dreamweaver cc 2018 it doesn't work. I use the 3.2.1 version of jquery jquery-3.2.1.js.

In my jsfiddle the selection is sorted alphabetically while in my page it doesn't.

var mylist = $('#list');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
mylist.empty().append(listitems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li>h</li>
<li>c</li>
<li>i</li>
<li>e</li>
<li>b</li>
<li>l</li>
<li>j</li>
<li>f</li>
<li>a</li>
<li>g</li>
<li>d</li>
<li>k</li>
<li>n</li>
<li>m</li>
</ul>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As I mentioned to my comment you problem probably is the timing of your html rendering and the javascript execution. You could try inserting your javascript code inside a document ready like this.

$( document ).ready(function() {
    var mylist = $('#list');
    var listitems = mylist.children('li').get();
    listitems.sort(function(a, b) {
        return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    mylist.empty().append(listitems);
});

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

...