javascript - jQuery 克隆改变的内容

标签 javascript jquery html dynamic clone

我正在尝试对刚刚使用 .html() 更改的内容运行 jQuery .clone()。但是,.clone 正在复制更改之前的内容。我想克隆更改后的内容。我该怎么做?

这是我的 HTML:

<div id="cloneThis">This text exists before .html() replaces it.</div>
<div id="cloneHere"></div>

这是我的 JS:

// This function copies #cloneThis content over to #cloneHere
function cloneStuff(){
  $('#cloneThis').clone().appendTo('#cloneHere');
}

function changeThenClone(){
  $("#cloneThis").html("This is new text that should be cloned.", cloneStuff());
}
// When this is run, cloneStuff() clones the old content, not the new content. 
changeThenClone();

如果您想查看实际效果,这里有一个相同的 codepen 演示:http://codepen.io/anon/pen/JoRWMQ

为什么 .clone() 不复制更改后的内容?如何让它克隆更改后的内容而不是旧内容?

最佳答案

您在 html() 函数完成实际 HTML 替换之前调用 cloneStuff()

试试这个:

$("#cloneThis").html("This is new text that should be cloned.");
cloneStuff();

此外,jQuery html() 方法仅接受 1 个参数(新的 HTML 内容),请参阅 documentation .

关于javascript - jQuery 克隆改变的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640544/

相关文章:

javascript - 如何防止 TinyMCE 5 删除\r\n

javascript - 在 jquery 对话框中加载 html 页面

javascript - 如何在 IE 中单击后退按钮时使表单值相同

javascript - 在javascript中加载带有类的php页面

javascript - slickgrid - 选择数据时自动滚动视口(viewport)

javascript - 无法使用javascript到达DIV的节点内容

html - 添加内联水平线

javascript - 如何将数组传递给ajax post?

php - 关于使用 javascript 在 css 中的一些文本样式

javascript - 如何在 Rollup.js 中进行缓存清除?