UL and LI with jQuery 3.2.1 running error

纵饮孤独 提交于 2019-12-13 23:26:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!