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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:56:15  来源:igfitidea点击:

How can I change the order of list elements using Jquery?

javascriptjquery

提问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

USe like this,

像这样使用,

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

eqselector selects the element with index. Then you can use before()or after()to change the postion .

eq选择器选择带有索引的元素。然后您可以使用before()after()来更改位置。

Fiddle

小提琴

回答by Amit Kumar

your jquery would be . you can use insertBefore.

你的 jquery 将是 . 你可以使用insertBefore。

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

DEMO

演示

回答by Rajaprabhu Aravindasamy

Try,

尝试,

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

DEMO

演示

or

或者

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

DEMO

演示

回答by Jon P

To make the first one last regardless of number of items:

无论项目数量如何,都要使第一个最后一个:

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

Demo

演示

回答by Rituraj ratan

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

DEMO

演示

or

或者

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

DEMO

演示

回答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/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

Fiddle

回答by hari

Demotry this,

演示试试这个,

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