仅限Javascript - 对一堆DIV进行排序 [英] Javascript only - sort a bunch of DIVs

查看:96
本文介绍了仅限Javascript - 对一堆DIV进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

最简单的DOM节点排序方式?

I有一个DIV列表,如下所示:

I have a list of DIVs, like this :

<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)得到如下结果:

and I want to sort them, using Javascript only (no Jquery) to have a result like this :

1
2
3
4
5

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

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)

非常感谢你的帮助!

以下是完整代码:

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


推荐答案

首先你要得到所有的div:

First you have to get all divs:

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

toSort 将是节点列表。你必须将它转换为数组:

toSort will be a NodeList. You have to transform it to an array:

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

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

and then you can pass a callback to the sort method:

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

编辑:正如@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]);
}

编辑:修正错误

DEMO

更新:如果您有这么多元素,可以像这样缓存ID:

Update: If you have so many elements, caching of the IDs could be done like so:

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

这篇关于仅限Javascript - 对一堆DIV进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆