问题
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>
What am I missing?
回答1:
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);
});
来源:https://stackoverflow.com/questions/47484876/ul-and-li-with-jquery-3-2-1-running-error