[英]How can I change the order of list elements using Jquery?
I have a ul li as below: 我有一个如下所示:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
How can I change the order of list elements using Jquery? 如何使用Jquery更改列表元素的顺序? So that on load, the new list should look like:
因此,在加载时,新列表应如下所示:
<ul id="list">
<li>2</li>
<li>1</li>
<li>3</li>
</ul>
Is it possible to achieve using Jquery? 是否可以使用Jquery实现?
If you use html like this: 如果您使用这样的html:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
you can use after
/ before
or appendTo
/ prependTo
to manipulate lists and other DOM
nodes: 你可以使用
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>
演示尝试这个,
alert($('li').eq(0).insertAfter($('li').eq(1)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.