6

要素をそれ自体の親の内部に移動する簡単な方法はありますか?

このような...

から:

<div class="test">hello 1</div>
<div class="test">hello 2</div>
<div class="test">hello 3</div>

に:

<div class="test">hello 1</div>
<div class="test">hello 3</div>
<div class="test">hello 2</div>

divを上または下に1ステップ移動するか、インデックスを使用して特定の位置にappendToを追加します。

4

3 に答える 3

12

.prev()これを使用して好きにすることができるはずです.next()(ここではjQuery関数として):

$.fn.moveUp = function() {
    $.each(this, function() {
         $(this).after($(this).prev());   
    });
};
$.fn.moveDown = function() {
    $.each(this, function() {
         $(this).before($(this).next());   
    });
};
$("div:eq(2)").moveUp(); //Would move hello 3 up
$("div:eq(0)").moveDown(); //Would move hello 1 down

JSFiddleデモ

于 2012-06-19T09:51:18.500 に答える
3

試す

$("div:eq(2)").after($("div:eq(0)"));

また

$("div:eq(2)").before($("div:eq(1)"))

:eq()はゼロベースであることを思い出してください。

于 2012-06-19T09:39:05.153 に答える
3
var child = $('#parent div'); // keep reference for further use
child.eq(2).insertBefore(child.eq(1));

デモ

于 2012-06-19T09:49:25.973 に答える