我正在尝试对刚刚使用 .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/