简体   繁体   中英

Sort an unordered list alphabetically

I want to sort an unordered list alphabetically. I've tried many different javascript solutions, not one of them worked (tested in Safari and Chrome). This is the code I would like to use:

 var activeLanguage = "de" function sortUL(selector) { var $ul = $(selector); $ul.find('li').sort(function(a, b) { var upA = $(a).text().toUpperCase(); var upB = $(b).text().toUpperCase(); return (upA < upB) ? -1 : (upA > upB) ? 1 : 0; }).appendTo(selector); }; $(document).ready(function() { sortUL("#WoodList"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <ul id="WoodList"> <li>Banana</li> <li>Catv</li> <li>Apple</li> <li>Orange</li> <li>Car</li> <li>Pear</li> <li>Banana</li> <li>Cat2</li> <li>Apple4</li> <li>Banana1</li> <li>Cat</li> <li>Apples</li> <li>Banana</li> <li>Cat</li> </ul> 

The list remains unsorted in the browser. Why is it not working ?

Here's a working example on JSFiddle: https://jsfiddle.net/vzbgzexc/

Make sure that you're loading jQuery. It doesn't look like anywhere in your code that you're loading jQuery, yet you're using $ . You're likely receiving an error in your browser's console similar to this:

ReferenceError: $ is not defined

Insert:

<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM