一组HTML元素的颠倒顺序

一组HTML元素的颠倒顺序

问题描述:

我有一组看起来像这样的div:

I have a set of divs that looks like this:

<div id="con">
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    <div> 5 </div>
</div>

但我希望它们翻转以使其看起来像这样:

But I want them to flip so that it looks like this:

<div> 5 </div>
<div> 4 </div>
<div> 3 </div>
<div> 2 </div>
<div> 1 </div>

这样,当新的< div> 添加到列表末尾。

So that when a new <div> is added it goes to the end of the list.

我该怎么做(或者有更好的方法呢?)

How can I do this (or is there a better way of doing this)?

包装为一个不错的jQuery函数,可用于任何选择集:

Wrapped up as a nice jQuery function available on any set of selections:

$.fn.reverseChildren = function() {
  return this.each(function(){
    var $this = $(this);
    $this.children().each(function(){ $this.prepend(this) });
  });
};
$('#con').reverseChildren();

证明: http://jsfiddle.net/R4t4X/1/

编辑:已修复为支持任意jQuery选择

fixed to support arbitrary jQuery selections