我有 2 个 div。
div1 和 div2。我想从 div1 获取所有内容并将它们 append 到 div2,然后淡出 div1。
我尝试过:
$('#div1').append('#div2');
$('#div1').fadeOut();
或
$('#div1').appendTo('#div2');
$('#div1').fadeOut();
和
$('#div1').html('#div2');
$('#div1').fadeOut();
但似乎没有一个对我有用。
我做错了什么?
最佳答案
.html()
的问题方法的特点是它将 DOM 元素转换为 HTML,反之亦然。您将失去绑定(bind)到这些元素的所有事件处理程序和数据。
使用 .contents()
[docs]相反:
$("#div1").contents().appendTo('#div2').end().fadeOut();
或者如果您想复制内容:
$("#div1").clone(true, true).contents().appendTo('#div2');
$("#div1").fadeOut();
<小时/>
使用方法时阅读文档总是有帮助的。例如
$('#div1').append('#div2');
将 append 字符串 #div2
到 ID 为 div1
的元素。文档说:
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
和
content: DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
类似于$('#div1').html('#div2');
:
htmlString: A string of HTML to set as the content of each matched element.
它只会替换 #div1
的内容与字符串 '#div2'
.
另一边
$('#div1').appendTo('#div2');
将 append ID 为 div1
的元素到 ID 为 div2
的元素:
Insert every element in the set of matched elements to the end of the target.
jQuery 文档非常好,我推荐阅读它。
关于jquery - 如何获取所有 div 的内容并将它们 append 到另一个 div 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8743208/