重新排序列表元素 - jQuery? [英] reorder list elements - jQuery?
问题描述
是否可以使用JavaScript或纯jQuery重新排序< li>
元素。所以如果我有一个如下的愚蠢列表:
Is it possible to reorder <li>
elements with JavaScript or pure jQuery. So if I have a silly list like the following:
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Cheese</li>
</ul>
我如何移动列表元素?比如将list元素与 Cheese
放在带有 Foo
的list元素之前,或者移动 Foo
到 Bar
之后。
How would I move the list elements around? Like put the list element with Cheese
before the list element with Foo
or move Foo
to after Bar
.
有可能吗?如果是这样,怎么样?
Is it possible? If so, how?
推荐答案
var ul = $("ul");
var li = ul.children("li");
li.detach().sort();
ul.append(li);
这是一个简单的例子,其中< li>
节点按默认顺序排序。我正在调用detach以避免删除与li节点相关的任何数据/事件。
This is a simple example where <li>
nodes are sorted by in some default order. I'm calling detach to avoid removing any data/events associated with the li nodes.
您可以传递函数进行排序,并使用自定义比较器进行排序还有。
You can pass a function to sort, and use a custom comparator to do the sorting as well.
li.detach().sort(function(a, b) {
// use whatever comparison you want between DOM nodes a and b
});
这篇关于重新排序列表元素 - jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!