一组HTML元素的颠倒顺序 [英] Reverse order of a set of HTML elements

查看:432
本文介绍了一组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

这篇关于一组HTML元素的颠倒顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆