使用 javascript 对 html 列表进行排序 [英] Sort an html list with javascript
问题描述
我有一组三个列表项,我想在页面加载时从高到低自动显示.最好使用 jquery 或 javascript.
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.
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
每个列表项都需要自己的 ID,因为它们每个都有单独的背景图像.数字必须是文本节点,以便用户可以编辑它们.
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.
推荐答案
这可能是最快的方法,因为它不使用 jQuery:
This will probably be the fastest way to do it, since it doesn't use 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);
}
调用函数如下:
sortList(document.getElementsByClassName('list')[0]);
你可以用同样的方式对其他列表进行排序,如果你在同一个页面上有其他元素和列表类,你应该给你的 ul 一个 id 并使用它来传递它.
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.
编辑
既然你提到你希望它在 pageLoad 上发生,我假设你希望它在 ul 在 DOM 中之后尽快发生,这意味着你应该将函数 sortList
添加到头部并在您的列表之后立即使用它,如下所示:
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:
<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>
这篇关于使用 javascript 对 html 列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!