javascript 如何使用 Jquery 更改列表元素的顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24502899/
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
How can I change the order of list elements using Jquery?
提问by Leo T Abraham
I have a ul li as below:
我有一个 ul li 如下:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
How can I change the order of list elements using Jquery? So that on load, the new list should look like:
如何使用 Jquery 更改列表元素的顺序?因此,在加载时,新列表应如下所示:
<ul id="list">
<li>2</li>
<li>1</li>
<li>3</li>
</ul>
Is it possible to achieve using Jquery?
是否可以使用 Jquery 实现?
回答by Anoop Joshi
回答by Amit Kumar
回答by Rajaprabhu Aravindasamy
回答by Jon P
回答by Rituraj ratan
回答by Pinal
If you use html like this:
如果您像这样使用 html:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
you can use after/beforeor appendTo/prependToto manipulate lists and other DOMnodes:
您可以使用after/before或appendTo/prependTo来操作列表和其他DOM节点:
var $list = $('#list'),
$items = $list.children(),
$firstItem = $items.first();
//remove first item from DOM
$firstItem.detach();
//set first item after second
$items.eq(1).after($firstItem);
And after this you will have such list:
在此之后,您将拥有这样的列表:
<ul id="list">
<li>2</li>
<li>1</li>
<li>3</li>
</ul>

