使用Javascript对无序列表进行排序 [英] Sort Unordered List with Javascript
问题描述
我一直在关注stackoverflow线程:
I have been looking at the stackoverflow thread:
但是对于我的场景,我有层次结构:
but for my scenario, I have the hierachy:
<ul><li><a href="http://www.google.com.au">NAME_TO_SORT_ON</a></li></ul>
根据此设置,如何从此处提到的线程修改解决方案以满足我的需求我想对NAME_TO_SORT_ON中找到的所有名字进行排序的情景吗?
Based on this set-up, how can I modify the solution from thread mentioned here to cater for my scenario which has a tag as I would like to sort on all the name found in NAME_TO_SORT_ON?
谢谢。
推荐答案
我建议使用基于jQuery的解决方案,因为一旦你开始进入多个DOM级别(例如,根据更深层次的元素内容对一个级别的兄弟姐妹进行排序)简单的排序机制崩溃了。这是一个非常粗略的解决方案 - 基本上吹走了现有的HTML并用原始文本模式替换它与其他HTML。我们可以通过实际改组DOM元素来做得更好:
I would recommend using a jQuery-based solution for this, because once you start getting into multiple DOM levels (e.g. sorting siblings at one level based on the contents of elements at a deeper level) the simple sort mechanism breaks down. It's an extremely rough solution - essentially blowing away the existing HTML and replacing it in raw text mode with other HTML. We can do better by actually shuffling the DOM elements around:
function sort(list, key) {
$($(list).get().reverse()).each(function(outer) {
var sorting = this;
$($(list).get().reverse()).each(function(inner) {
if($(key, this).text().localeCompare($(key, sorting).text()) > 0) {
this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
}
});
});
}
要使用它,我们将选择器传递给列表和选择器用于找到我们要排序的键:
To use it, we pass in a selector to the list and a selector to use to locate the key we want to sort on:
<ul class="toBeSorted">
<li><a href="...">sort me</a></li>
</ul>
<script type="text/javascript">
sort('ul.toBeSorted>li', 'a');
//we want to sort the <li>'s in ul.toBeSorted;
//and we want to use the text of the first and only <a>
//in each item as the sort key
</script>
这篇关于使用Javascript对无序列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!