仅限 Javascript - 对一堆 DIV 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5066925/
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
Javascript only - sort a bunch of DIVs
提问by jrm
Possible Duplicate:
Easiest way to sort DOM nodes?
可能的重复:
对 DOM 节点进行排序的最简单方法?
I have a list of DIVs, like this :
我有一个 DIV 列表,如下所示:
<div id="list">
<div id="categorie5.1-4">4</div>
<div id="categorie5.1-3">3</div>
<div id="categorie5.1-5">5</div>
<div id="categorie5.1-1">1</div>
<div id="categorie5.1-2">2</div>
</div>
and I want to sort them, using Javascript only (no Jquery) to have a result like this :
我想对它们进行排序,只使用 Javascript(没有 Jquery)来得到这样的结果:
1
2
3
4
5
If needed, I can use the end of the DIV ids : "categorie5.1-4" (server-side I can define the DIV ids to embedded the wanted order)
如果需要,我可以使用DIV id的端:“categorie5.1- 4”(服务器侧I可以定义DIV id与嵌入在希望顺序)
Thank you very much for your help!
非常感谢您的帮助!
Here is the complete code :
这是完整的代码:
<html>
<head>
<script type="text/javascript">
function sortdiv() {
var container = document.getElementById("list");
var elements = container.childNodes;
var sortMe = [];
for (var i=0; i<elements.length; i++) {
if (!elements[i].id) {
continue;
}
var sortPart = elements[i].id.split("-");
if (sortPart.length > 1) {
sortMe.push([ 1 * sortPart[1] , elements[i] ]);
}
}
sortMe.sort(function(x, y) {
return x[0] - y[0];
});
for (var i=0; i<sortMe.length; i++) {
container.appendChild(sortMe[i][1]);
}
document.getElementById("button").innerHTML = "done.";
}
</script>
</head>
<body>
<div id="list">
<div id="categorie5.1-4">4</div>
<div id="categorie5.1-3">3</div>
<div id="categorie5.1-5">5</div>
<div id="categorie5.1-1">1</div>
<div id="categorie5.1-2">2</div>
</div>
<div id="button"><a href="#" onclick="sortdiv();">sort!</a></div>
</body>
</html>
回答by Felix Kling
First you have to get all divs:
首先,您必须获得所有 div:
var toSort = document.getElementById('list').children;
toSort
will be a NodeList
. You have to transform it to an array:
toSort
将是一个NodeList
. 您必须将其转换为数组:
toSort = Array.prototype.slice.call(toSort, 0);
and then you can pass a callback to the sort
method:
然后您可以将回调传递给该sort
方法:
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
return aord - bord;
});
Edit: As @Lekensteyn already noted, comparing IDs only works if you have only single digit numbers. Fixed it to support arbitrary numbers.
编辑:正如@Lekensteyn 已经指出的,只有当您只有一位数时,比较 ID 才有效。修复它以支持任意数字。
You have to loop over this array and append the elements again:
您必须遍历此数组并再次附加元素:
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
Edit: fixed typo
编辑:修正错别字
Update:If you have so many elements, caching of the IDs could be done like so:
更新:如果您有这么多元素,可以像这样缓存 ID:
var cache = {
add: function(id) {
var n = +id.split('-')[1];
this[id] = n;
return n;
}
};
toSort.sort(function(a, b) {
var aord = cache[a.id] || cache.add(a.id);
var bord = cache[b.id] || cache.add(b.id);
return aord - bord;
});
回答by Lekensteyn
You should put the elements in an array, run a sort function over the elements, and re-append the sorted elements to the container.
您应该将元素放入数组中,对元素运行排序函数,然后将排序后的元素重新附加到容器中。
// container is <div id="list">
var container = document.getElementById("list");
// all elements below <div id="list">
var elements = container.childNodes;
// temporary storage for elements which will be sorted
var sortMe = [];
// iterate through all elements in <div id="list">
for (var i=0; i<elements.length; i++) {
// skip nodes without an ID, comment blocks for example
if (!elements[i].id) {
continue;
}
var sortPart = elements[i].id.split("-");
// only add the element for sorting if it has a dash in it
if (sortPart.length > 1) {
/*
* prepare the ID for faster comparison
* array will contain:
* [0] => number which will be used for sorting
* [1] => element
* 1 * something is the fastest way I know to convert a string to a
* number. It should be a number to make it sort in a natural way,
* so that it will be sorted as 1, 2, 10, 20, and not 1, 10, 2, 20
*/
sortMe.push([ 1 * sortPart[1] , elements[i] ]);
}
}
// sort the array sortMe, elements with the lowest ID will be first
sortMe.sort(function(x, y) {
// remember that the first array element is the number, used for comparison
return x[0] - y[0];
});
// finally append the sorted elements again, the old element will be moved to
// the new position
for (var i=0; i<sortMe.length; i++) {
// remember that the second array element contains the element itself
container.appendChild(sortMe[i][1]);
}
You can test this code at http://jsfiddle.net/4gkDt/1/
您可以在http://jsfiddle.net/4gkDt/1/测试此代码
回答by madmik3
Javascript arrays has a sort function.
Javascript 数组具有排序功能。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
you can make sort the childnodes list node on innerHTML (in your example) or some other key.
您可以在innerHTML(在您的示例中)或其他一些键上对childnodes列表节点进行排序。
This shows how to get the list node http://codingrecipes.com/documentgetelementbyid-on-all-browsers-cross-browser-getelementbyid
这显示了如何获取列表节点 http://codingrecipes.com/documentgetelementbyid-on-all-browsers-cross-browser-getelementbyid
so something like
所以像
document.getElementById("list").children.sort(yourSortFunction)