【问题标题】:Javascript only - sort a bunch of DIVs [duplicate]仅限 Javascript - 对一堆 DIV 进行排序 [重复]
【发布时间】:2011-02-22 00:31:43
【问题描述】:

可能重复:
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>

【问题讨论】:

  • “一束”10、100、1000有多少?
  • 您知道,您可能应该将最终代码移至 answer。 (作为奖励,你会得到更多的代表!)

标签: javascript


【解决方案1】:

首先你必须得到所有的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;
});

【讨论】:

  • 非常感谢 Felix - 我理解这个概念,但我是 js 初学者,当我尝试实施您的解决方案时,我看不到排序的结果...我需要触发某些东西以查看 DIV 重新排列?
  • @jrm:嘿,不,我只是在代码中有错字。看我的演示jsfiddle.net/fkling/nXkDp
  • 非常感谢您的帮助 Felix,您的代码完美地完成了这项工作 - Leken 的代码似乎更复杂一些,并且可以很好地处理一些异常(无效 ID、cmets 等)
  • @jrm: 最适合你的 :) 关于无效 ID:我假设你只处理具有正确 ID 的元素。没有正确 ID 的元素应该怎么办?他们应该被删除吗?放在最后?关于 cmets:children 只返回元素节点(所以没有 cmets、文本节点等)
  • @Felix,感谢您的帮助,我正在使用您的代码,这似乎非常优化 - 我还有一个问题,是否可以在 Javascript 中使用“盲字符”?像 document.getElementById('qwerty' + i + '*').innerHTML = "text",其中 * 为 0 或 1 或多个字符? (当然,如果只有一个 ID 以 'qwerty + i' 开头的 div
【解决方案2】:

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

// 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/ 测试此代码

【讨论】:

  • 注意排序功能可以改进,如果你的ID像categorie5.1-X,这个排序功能就足够了。否则,如果您有 categorie5.1-Xcategorie-5.1-XY 之类的 ID,则必须从 ID 中提取 X 或 XY 部分,并将其转换为数字,以防止像 1、11、2 这样的排序列表, 21, 3, 4, ...
  • 非常感谢您的帮助 - 我是否需要“更新”(“回显”/“写入”)某些内容才能看到结果?
  • (是的,我会有一些 -XY ID...)
  • 我刚刚优化了脚本。 sort 函数可以对一个元素进行多次操作,因此与其每次都从 ID 中检索数字,不如将检索到的数字存储起来进行比较。
  • 谢谢你,真的!我试图在一个简单的 html 文件中实现,但是“for (var i=0;i
【解决方案3】:

Javascript 数组具有排序功能。

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

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

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

有点像

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

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2019-06-11
    相关资源
    最近更新 更多