jQuery移动DOM元素在父元素内部

6

有没有一种简单的方法将元素移动到其父元素内部?

就像这样...

从:

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

to:

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

要么将一个div向上或向下移动一步,要么使用索引在特定位置进行appendTo。


这两个元素有什么特点?你如何选择要移动的元素,需要将其移动到哪里? - Mattias Buelens
我使用点击处理程序进行选择。然后,我使用所点击元素的索引。 - user1121487
好的,那么点击的元素应该放在哪里?它应该移动到列表中的最后一个元素之后吗?你如何确定新位置? - Mattias Buelens
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演示


3

尝试

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

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

请记住::eq() 是从 0 开始计数的。


你难道不能直接执行 $("div:eq(2)").after($("div:eq(3)")) 这个语句吗?或者那样行不行呢? - h2ooooooo

3
var child = $('#parent div'); // keep reference for further use
child.eq(2).insertBefore(child.eq(1));

DEMO


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接