jQuery在父内部移动DOM元素

use*_*487 6 jquery element

有没有一种简单的方法可以在自己的父元素中移动元素?

像这样...

从:

<div class="test">hello 1</div>
<div class="test">hello 2</div>
<div class="test">hello 3</div>
Run Code Online (Sandbox Code Playgroud)

至:

<div class="test">hello 1</div>
<div class="test">hello 3</div>
<div class="test">hello 2</div>
Run Code Online (Sandbox Code Playgroud)

将div向上或向下移动一步,或使用索引将appendTo移动到特定位置.

h2o*_*ooo 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
Run Code Online (Sandbox Code Playgroud)

JSFiddle演示