使用jquery根据li元素排序ul列表?
我正在使用
- 元素创建一个水平列表,但我想要做的是根据
- 元素按字母顺序放置每个
- 元素。 例如
- Name
- Surname
- Unit
- City
- John
- Boe
- BA
- NY
- Jane
- Doe
- MA
- CA
并根据Surname字段将它们整理好。 用jquery有什么办法吗?
提前致谢
//编辑//
我正在使用的代码是这样的
$.ajax({ type: 'GET', url: 'list.php', data: 'id='+id, dataType: 'xml', success: function(data) { var xml; if (typeof data == "string") { xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = false; xml.loadXML(data); } else { xml = data; } $(xml).find('item').each(function(){ var id = $(this).find("id").text(); var name = $(this).find("name").text(); var surname = $(this).find("surname").text(); var units = $(this).find("units").text(); var city = $(this).find("city").text(); $("#listContainer").append('
- '+name+'
- '+surname+'
- '+units+'
- '+city+'
工作演示
$('.grid ul:gt(0)').each(function() { var txt1 = $(this).children('li:eq(1)').text(); $(this).data('name', txt1); }); var items = $('.grid ul'); items.sort(function(a, b) { var chA = $(a).data('name'); var chB = $(b).data('name'); if (chA < chB) return -1; if (chA > chB) return 1; return 0; }); var grid = $('.grid'); $(grid).append(items);
和HTML
- Name
- Surname
- Unit
- City
- John
- Boe
- BA
- NY
- Jane
- Doe
- MA
- CA
- Lin
- Zyan
- MA
- OR
- Matt
- Albright
- MA
- CA
将导致:
这个怎么运作:
我们在所需的li
找文本:eq()
我们将此文本设置为每个UL元素的jQuery .data()。
我们只是按检索的.data()文本对ul
进行排序 – 按字母顺序排列!快乐的编码!