按字母顺序对无序列表进行排序 [英] Sort an unordered list alphabetically

查看:64
本文介绍了按字母顺序对无序列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按字母顺序对无序列表进行排序.我尝试了许多不同的javascript解决方案,但没有一个能用(在Safari和Chrome中测试过).这是我要使用的代码:

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 ?

推荐答案

这是JSFiddle上的一个有效示例: https://jsfiddle.net/vzbgzexc/

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

确保您正在加载jQuery.加载jQuery看起来不像代码中的任何地方,但是您正在使用 $ .您可能会在浏览器的控制台中收到类似于以下内容的错误:

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

插入:

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

希望有帮助!

这篇关于按字母顺序对无序列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆