jQuery jQuery反转子元素的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5347839/
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-08-26 19:00:37  来源:igfitidea点击:

jQuery reversing the order of child elements

jquery

提问by tilleryj

What is the best way to reverse the order of child elements with jQuery.

使用 jQuery 反转子元素顺序的最佳方法是什么?

For example, if I start with:

例如,如果我开始:

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

I want to end up with this:

我想以这样的方式结束:

<ul>
  <li>C</li>
  <li>B</li>
  <li>A</li>
</ul>

回答by Anurag

var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());

回答by undefined

Edit: Anurag's answeris better than mine.

编辑:Anurag 的回答比我的好。

ul = $('#my-ul'); // your parent ul element
ul.children().each(function(i,li){ul.prepend(li)})

If you call .prepend() on an object containing more than one element, the element being appended will be cloned for the additional target elements after the first, so be sure you're only selecting a single element.

如果在包含多个元素的对象上调用 .prepend() ,则附加的元素将在第一个之后为其他目标元素克隆,因此请确保您只选择了一个元素。

回答by Kyle Rogers

Try this:

尝试这个:

$(function() {
  $.fn.reverse = [].reverse;
  var x = $('li');
  $('ul').empty().append(x.reverse());
});

回答by Meer

All the answer given before me are best but you can try this also

在我之前给出的所有答案都是最好的,但你也可以试试这个

$('#btnrev').click(function(){

$('ul').html($('ul').find('li').get().reverse());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

<button id="btnrev">
click
</button>

回答by Dieter Bender

oneliner:

单线:

$('ul').append($('ul>').detach().get().reverse());

回答by Dieter Bender

No Jquery Solution

没有 Jquery 解决方案

Element.prototype.reverse = function(){
    var c = [].slice.call(this.children).reverse();
    while (this.firstChild) { this.removeChild(this.firstChild); };
    c.forEach(function( child ){ this.appendChild(child) }.bind(this))
}

And use like :

并使用类似:

document.querySelector('ul').reverse(); // children are now reversed