我想将一个DIV元素移动到另一个元素中。例如,我想移动此(包括所有子对象):
<div id="source">
...
</div>
在这方面:
<div id="destination">
...
</div>
所以我有这个:
<div id="destination">
<div id="source">
...
</div>
</div>
我想将一个DIV元素移动到另一个元素中。例如,我想移动此(包括所有子对象):
<div id="source">
...
</div>
在这方面:
<div id="destination">
...
</div>
所以我有这个:
<div id="destination">
<div id="source">
...
</div>
</div>
当前回答
如果要放置元素的div中包含内容,并且希望元素显示在主要内容之后:
$("#destination").append($("#source"));
如果要放置元素的div中包含内容,并且希望在主要内容之前显示元素:
$("#destination").prepend($("#source"));
如果要放置元素的div为空,或者要完全替换它:
$("#element").html('<div id="source">...</div>');
如果要在上述任一项之前复制元素:
$("#destination").append($("#source").clone());
// etc.
其他回答
如果要放置元素的div中包含内容,并且希望元素显示在主要内容之后:
$("#destination").append($("#source"));
如果要放置元素的div中包含内容,并且希望在主要内容之前显示元素:
$("#destination").prepend($("#source"));
如果要放置元素的div为空,或者要完全替换它:
$("#element").html('<div id="source">...</div>');
如果要在上述任一项之前复制元素:
$("#destination").append($("#source").clone());
// etc.
我需要将内容从一个容器移动到另一个容器,包括所有事件侦听器。jQuery没有实现它的方法,但标准的DOM函数appendChild可以实现。
// Assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);
使用appendChild删除.source*并将其放入目标,包括其事件侦听器:Node.appendChild()(MDN)
使用普通JavaScript解决方案:
// Declare a fragment:
var fragment = document.createDocumentFragment();
// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));
// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);
过来看。
我刚刚使用了:
$('#source').prependTo('#destination');
我从这里抓起的。
如果您想要快速演示并了解有关如何移动元素的更多详细信息,请尝试以下链接:
http://html-tuts.com/move-div-in-another-div-with-jquery
下面是一个简短的示例:
要在元素上方移动:
$('.whatToMove').insertBefore('.whereToMove');
要在元素后移动,请执行以下操作:
$('.whatToMove').insertAfter('.whereToMove');
要在元素内移动,请在该容器内的所有元素上方:
$('.whatToMove').prependTo('.whereToMove');
要在元素内移动,请在该容器内的所有元素之后:
$('.whatToMove').appendTo('.whereToMove');