简体   繁体   English

如何使用Jquery更改列表元素的顺序?

[英]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实现?

USe like this, 像这样使用,

$("#list li:eq(0)").before($("#list li:eq(1)"));

eq selector selects the element with index. eq选择器选择具有索引的元素。 Then you can use before() or after() to change the postion . 然后你可以使用before()after()来改变位置。

Fiddle 小提琴

your jquery would be . 你的jquery会。 you can use insertBefore. 你可以使用insertBefore。

$('#list').find('li:eq(1)').insertBefore('li:eq(0)');

DEMO DEMO

Try, 尝试,

var lists = $('#list li');
lists.filter(':contains(2)').insertBefore(lists.filter(':contains(1)'));

DEMO DEMO

or 要么

var lists = $('#list li');
lists.filter(':nth-child(2)').insertBefore(lists.filter(':nth-child(1)'));

DEMO DEMO

To make the first one last regardless of number of items: 无论项目数量多少,要使第一个最后一个:

$("#list li:last").after($("#list li:first"));

Demo 演示

   $("#list").prepend($("li:eq(1)"));

DEMO DEMO

or 要么

 $("li:eq(1)").prependTo("#list");

DEMO DEMO

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

Fiddle

演示尝试这个,

  alert($('li').eq(0).insertAfter($('li').eq(1)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM