17

次のようなdivのセットがあります。

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

しかし、次のように反転させたいと思います。

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

そのため、新しい<div>ものが追加されると、リストの最後に移動します。

これを行うにはどうすればよいですか (または、これを行うためのより良い方法はありますか)?

4

7 に答える 7

18

任意の選択セットで使用できる素敵な jQuery 関数としてまとめられています。

$.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選択をサポートするように修正

于 2011-10-30T13:05:09.017 に答える
6

ライブラリなし:

function reverseChildNodes(node) {
    var parentNode = node.parentNode, nextSibling = node.nextSibling,
        frag = node.ownerDocument.createDocumentFragment();
    parentNode.removeChild(node);
    while(node.lastChild)
        frag.appendChild(node.lastChild);
    node.appendChild(frag);
    parentNode.insertBefore(node, nextSibling);
    return node;
}

reverseChildNodes(document.getElementById('con'));

jQueryスタイル:

$.fn.reverseChildNodes = (function() {
    function reverseChildNodes(node) {
        var parentNode = node.parentNode, nextSibling = node.nextSibling,
            frag = node.ownerDocument.createDocumentFragment();
        parentNode.removeChild(node);
        while(node.lastChild)
            frag.appendChild(node.lastChild);
        node.appendChild(frag);
        parentNode.insertBefore(node, nextSibling);
        return node;
    };
    return function() {
        this.each(function() {
            reverseChildNodes(this);
        });
        return this;
    };
})();

$('#con').reverseChildNodes();

jsPerfテスト

于 2011-10-30T05:00:15.923 に答える
3

一方通行:

function flip(){
 var l=$('#con > div').length,i=1;
 while(i<l){
   $('#con > div').filter(':eq(' + i + ')').prependTo($('#con'));
   i++;
 }
}
于 2011-10-30T01:38:49.530 に答える
0

別の (より単純な?) バニラ JavaScript 応答: http://jsfiddle.net/d9fNv/

var con = document.getElementById('con');
var els = Array.prototype.slice.call(con.childNodes);
for (var i = els.length -1; i>=0; i--) {
    con.appendChild(els[i]);
}

または、より短いが効率の悪い方法: http://jsfiddle.net/d9fNv/1/

var con = document.getElementById('con');
Array.prototype.slice.call(con.childNodes).reverse().forEach(function(el) {
    con.appendChild(el);
});
于 2011-10-30T23:06:16.723 に答える