简体   繁体   English

如何对锚标记内的无序列表进行排序

[英]How to sort an unordered list inside an anchor tag

I have the following DOM structure (unordered list), that I would like to sort on the a href tag name using jQuery.我有以下 DOM 结构(无序列表),我想使用 jQuery 对a href标签名称进行排序。

Structure is as follows:结构如下:

<div id="refmenu">
<ul id="list">
<li><a href="....">Google</a></li>
<li><a href="....">Apple</a></li>
<li><a href="....">IBM</a></li>
<li><a href="....">Yahoo!</a></li>
<li><a href="....">Hotmail</a></li>
</ul>
</div>

Based on the above, would like to be able to run this through a jQuery function that will sort the unordered list names alphabetically, obviously also keeping the a href link together with the anchor tag names.基于上述内容,希望能够通过一个 jQuery 函数来运行它,该函数将按字母顺序对无序列表名称进行排序,显然还将a href链接与锚标记名称保持在一起。

Give TinySort plugin a look at, it sorts child nodes by contents or attributes: Example看看TinySort插件,它按内容或属性对子节点进行排序: 示例

Edit-编辑-

$("div#refmenu>ul#platsys>li").tsort("a.title"); 

Also there is no reason for the extra filtering before the id selector , selecting by tag name does not speed up the performance when selecting by id.也没有理由在id 选择器之前进行额外的过滤,按标签名称选择在按id 选择时不会加快性能 Also your id name for your ul is not platsys, so I don't know where you got that from it should be ul#list>li , but to shorten all that extra unneeded code I would have此外,你的ul 的id 名称不是 platsys,所以我不知道你从哪里得到的应该是ul#list>li ,但为了缩短所有额外不需要的代码,我会

$("#refmenu>#list>li").tsort("a.title");

actually from your html I think that would be the same as:实际上从你的 html 来看,我认为这与:

$("#list>li").tsort("a.title");

you can try List.js which will extend your list features to extremes as您可以尝试List.js它将您的列表功能扩展到极端

  1. it's lightweight [only 3K script]它是轻量级的 [只有 3K 脚本]
  2. easy to implement in your existing HTML table using class易于使用类在现有的 HTML 表中实现
  3. searchable, sortable and filterable可搜索、可排序和可过滤

HTML HTML

<div id="my-list">
    <ul class="list">
       <li>
           <h3 class="name">Luke</h3>
       </li>
       <li>
           <h3 class="name">John</h3>
       </li>
    </ul>
</div>

Javascript Javascript

var options = {
    valueNames: ['name']
};
var myList = new List('my-list', options);

Try this:试试这个:

var list = $("#list"),
    listItems = Array.prototype.slice.call(list.find("li"));
listItems.sort(function(a, b) {
    a = $("a", a).text(), b = $("a", b).text();
    return a < b ? -1 : a > b ? 1 : 0;
});
listItems.forEach(function(val) {
    list.append($(val).remove());
});

If you want to sort on a different criteria than the anchor text, replace text() by whatever you want.如果您想按照与锚文本不同的标准进行排序,请用您想要的任何内容替换text()

Surely all your href's here are going to start with http:// or www?当然,您这里的所有 href 都将以 http:// 或 www 开头吗? How will sorting that help?排序将如何帮助?

Would an ordered list not do the job?有序列表不能完成这项工作吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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