我想将一个 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);
看看吧。
网友回答:
您可能希望使用该函数(添加到元素的末尾):appendTo
$("#source").appendTo("#destination");
或者,您可以使用该函数(添加到元素的开头):prependTo
$("#source").prependTo("#destination");
例:
$("#appendTo").click(function() {
$("#moveMeIntoMain").appendTo($("#main"));
});
$("#prependTo").click(function() {
$("#moveMeIntoMain").prependTo($("#main"));
});
#main {
border: 2px solid blue;
min-height: 100px;
}
.moveMeIntoMain {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">main</div>
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>
<button id="appendTo">appendTo main</button>
<button id="prependTo">prependTo main</button>
网友回答:
我的解决方案:
移动:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
复制:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
请注意 .detach() 的用法。复制时,请注意不要复制 ID。
模板简介:该模板名称为【我想将一个 DIV 元素移动到另一个元素中?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【HTML】栏目查找您需要的精美模板。