【问题标题】:jQuery Cloning Altered ContentjQuery 克隆更改的内容
【发布时间】:2015-02-22 18:53:02
【问题描述】:

我正在尝试对刚刚使用 .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() 不复制更改的内容?如何让它克隆更改的内容而不是旧内容?

【问题讨论】:

  • 只使用简单的链接:$("#cloneThis").html("This is new text that should be cloned.").clone().appendTo('#cloneHere')

标签: javascript jquery html dynamic clone


【解决方案1】:

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

试试这个:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多