仅限Javascript - 对一堆DIV进行排序

时间:2011-02-21 14:06:06

标签: javascript

  

可能重复:
  Easiest way to sort DOM nodes?

我有一个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>

我希望对它们进行排序,只使用Javascript(没有Jquery)得到这样的结果:

1
2
3
4
5

如果需要,我可以使用DIV ID的结尾:“categorie5.1- 4 ”(服务器端我可以定义DIV ID以嵌入所需订单)

非常感谢你的帮助!


以下是完整的代码:

<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>

3 个答案:

答案 0 :(得分:14)

首先你要得到所有的div:

var toSort = document.getElementById('list').children;

toSort将是NodeList。你必须将它转换为数组:

toSort = Array.prototype.slice.call(toSort, 0);

然后您可以将回调传递给sort方法:

toSort.sort(function(a, b) {
    var aord = +a.id.split('-')[1];
    var bord = +b.id.split('-')[1];
    return aord - bord;
});

编辑:正如@Lekensteyn已经指出的那样,比较ID仅在您只有一位数时才有效。修正了它以支持任意数字。

你必须遍历这个数组并再次附加元素:

var parent = document.getElementById('list');
parent.innerHTML = "";

for(var i = 0, l = toSort.length; i < l; i++) {
    parent.appendChild(toSort[i]);
}

编辑:修正错误

DEMO

更新:如果您有这么多元素,可以像这样缓存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;
});

答案 1 :(得分:1)

您应该将元素放在数组中,对元素运行排序函数,然后将已排序的元素重新附加到容器中。

// 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]);
}

您可以在http://jsfiddle.net/4gkDt/1/

测试此代码

答案 2 :(得分:0)

Javascript数组有一个排序功能。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

你可以在innerHTML(在你的例子中)或其他一些上对childnodes列表节点进行排序 键。

这显示了如何获取列表节点 http://codingrecipes.com/documentgetelementbyid-on-all-browsers-cross-browser-getelementbyid

类似

document.getElementById("list").children.sort(yourSortFunction)