我想将一个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>
当前回答
使用普通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');
我从这里抓起的。
使用普通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);
过来看。
我的解决方案:
移动:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
副本:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
注意.detach()的用法。复制时,请注意不要复制ID。
appendChild正是这样做的——基本上是剪切粘贴。
它将移动选定的元素及其所有子节点。
我需要将内容从一个容器移动到另一个容器,包括所有事件侦听器。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)