使用 javascript 对 html 列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8837191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort an html list with javascript
提问by danssker
I have a set of three list items that I would like to automatically display from high to low on page load. Ideally using jquery or javascript.
我有一组三个列表项,我希望在页面加载时从高到低自动显示。理想情况下使用 jquery 或 javascript。
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
Each list item needs its own ID because they each have individual background images. The numbers must text nodes so that a user can edit them.
每个列表项都需要自己的 ID,因为它们每个都有单独的背景图像。数字必须是文本节点,以便用户可以编辑它们。
回答by Paul
This will probably be the fastest way to do it, since it doesn't use jQuery:
这可能是最快的方法,因为它不使用 jQuery:
function sortList(ul){
var new_ul = ul.cloneNode(false);
// Add all lis to an array
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
// Sort the lis in descending order
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) -
parseInt(a.childNodes[0].data , 10);
});
// Add them into the ul in order
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
Call the function like:
调用函数如下:
sortList(document.getElementsByClassName('list')[0]);
You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.
你可以用同样的方式对其他列表进行排序,如果你在同一个页面上有其他元素和列表类,你应该给你的 ul 一个 id 并使用它来传递它。
Edit
编辑
Since you mentioned that you want it to happen on pageLoad, I'm assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList
to the head of your page and use it immediately after your list like this:
既然你提到你希望它发生在 pageLoad 上,我假设你希望它在 ul 在 DOM 中之后尽快发生,这意味着你应该将该函数添加sortList
到页面的头部并在你的列表之后立即使用它这个:
<head>
...
<script type="text/javascript">
function sortList(ul){
var new_ul = ul.cloneNode(false);
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) - parseInt(a.childNodes[0].data , 10);
});
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
</script>
</head>
<body>
...
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
<script type="text/javascript">
!function(){
var uls = document.getElementsByTagName('ul');
sortList( uls[uls.length - 1] );
}();
</script>
...
</body>
回答by AbdullahDiaa
you can use this lightweight jquery plugin List.jscause
你可以使用这个轻量级的 jquery 插件List.js原因
- it's lightweight [only 3K script]
- easy to implement in your existing HTML table using class
- searchable, sortable and filterable
- 它是轻量级的 [只有 3K 脚本]
- 易于使用类在现有的 HTML 表中实现
- 可搜索、可排序和可过滤
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);
回答by Francis
You can try this
你可以试试这个
var ul = $(".list:first");
var arr = $.makeArray(ul.children("li"));
arr.sort(function(a, b) {
var textA = +$(a).text();
var textB = +$(b).text();
if (textA < textB) return -1;
if (textA > textB) return 1;
return 0;
});
ul.empty();
$.each(arr, function() {
ul.append(this);
});
Live example : http://jsfiddle.net/B7hdx/1
现场示例:http: //jsfiddle.net/B7hdx/1
回答by Sjeiti
There's also this small jQuery plugin. Which would make your sort nothing more than:
还有这个小的 jQuery 插件。这将使您的排序无非是:
$('.list>li').tsort({attr:'id'});
回答by jfriend00
This code will sort that list assuming there is only one .list
item:
假设只有一个.list
项目,此代码将对该列表进行排序:
function sortList(selector) {
var parent$ = $(selector);
parent$.find("li").detach().sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
parent$.append(el);
});
}
sortList(".list");
You can see it work here: http://jsfiddle.net/jfriend00/FjuMB/
你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/FjuMB/
To explain how it works:
解释它是如何工作的:
- It gets the .list parent object.
- It finds all the
<li>
child objects. - It removes all the
<li>
child objects from the DOM, but preserves their data - It sorts the li objects using a custom sort function
- The custom sort function gets the HTML in the li tag and converts it to a number
- Then, traversing the array in the newly sorted order, each li tag is appended back onto the original parent.
- 它获取 .list 父对象。
- 它找到所有的
<li>
子对象。 - 它
<li>
从 DOM 中删除所有子对象,但保留它们的数据 - 它使用自定义排序函数对 li 对象进行排序
- 自定义排序函数获取li标签中的HTML并将其转换为数字
- 然后,以新排序的顺序遍历数组,将每个 li 标记附加回原始父级。
The result is that they are displayed in sorted order.
结果是它们按排序顺序显示。
Edit:
编辑:
This improved version will even sort multiple list objects at once:
这个改进的版本甚至可以一次对多个列表对象进行排序:
function sortList(selector) {
$(selector).find("li").sort(function(a, b) {
return(Number(a.innerHTML) - Number(b.innerHTML));
}).each(function(index, el) {
$(el).parent().append(el);
});
}
sortList(".list");
回答by bob
Non jquery version (vanilla javascript)
非 jquery 版本(vanilla javascript)
Benefits: the list is sorted in place, which doesn't destroy the LI's nor remove any events that may be associated with them. It just shuffles things around
优点:列表按原位排序,不会破坏 LI,也不会删除任何可能与它们相关联的事件。它只是洗牌
Added an id to the UL:
向 UL 添加了一个 id:
<ul id="myList" class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
and the vanilla javascript (no jquery)
和 vanilla javascript(没有 jquery)
// Grab a reference to the UL
var container = document.getElementById("myList");
// Gather all the LI's from the container
var contents = container.querySelectorAll("li");
// The querySelector doesn't return a traditional array
// that we can sort, so we'll need to convert the contents
// to a normal array.
var list = [];
for(var i=0; i<contents.length; i++){
list.push(contents[i]);
}
// Sort based on innerHTML (sorts "in place")
list.sort(function(a, b){
var aa = parseInt(a.innerHTML);
var bb = parseInt(b.innerHTML);
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});
// We'll reverse the array because our shuffle runs backwards
list.reverse();
// Shuffle the order based on the order of our list array.
for(var i=0; i<list.length; i++){
console.log(list[i].innerHTML);
container.insertBefore(list[i], container.firstChild);
}
And the fiddle proof: https://jsfiddle.net/L27gpnh6/1/
和小提琴证明:https: //jsfiddle.net/L27gpnh6/1/
回答by James Allardice
One method could be to sort an array(well, a jQuery object) of the li
elements and replace the contents (using the html
method) of the ul
with the sorted array of elements:
一种方法可能是对元素的数组(好吧,一个 jQuery 对象)进行排序li
,并将 的内容(使用html
方法)替换为ul
已排序的元素数组:
$(".list").html($(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}));
Here's a working example.
这是一个工作示例。
回答by jabclab
Something like this should help:
这样的事情应该有帮助:
var $parent = $(".list");
$(".list li").sort(function (a, b) {
return window.parseInt($(a).text(), 10) - window.parseInt($(b).text(), 10);
}).remove().each(function () {
$parent.append($(this));
});
回答by dfsq
Sort jQuery collection as usual array and then append each element back in correct order.
像往常一样对 jQuery 集合进行排序,然后以正确的顺序附加每个元素。
$(".list li").sort(function(a, b) {
return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}).appendTo('.list');
回答by Skyrim
using jQuery for help:
使用 jQuery 寻求帮助:
var sortFunction = function(a, b) {
return (+($(b).text())) - (+($(a).text()));
}
var lis = $('ul.list li');
lis = Array.prototype.sort.call(lis, sortFunction);
for (var i = 0; i < lis.length; i++) {
$('ul.list').append(lis[i]);
}