jquery - 如何获取所有 div 的内容并将它们 append 到另一个 div 中?

标签 jquery append

我有 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/

相关文章:

r - 在循环中 append 列表 (R)

javascript - 如何使用jquery追加列表

ruby - 在 Ruby 中 append 到 JSON 数组

javascript - 获取输入值并将其用作 JS/jQuery 的数组

jquery - 回调中链接 jQuery 动画的问题

jquery - 如何在页面中居中 Diaporama

python - append to a sublist append 到每个子列表

包含函数/范围问题的 Javascript 对象

javascript - jQuery 循环数组,其中包含 html2canvas 的 div 内容

Java keyTool - 将主要/次要中间证书 append 到 keystore