gpt4 book ai didi

javascript - jQuery 不会 append 在文档就绪时声明的克隆

转载 作者:行者123 更新时间:2023-11-29 17:10:07 26 4
gpt4 key购买 nike

我的问题是,如果我在页面加载时创建一个克隆变量,jQuery 只会 append 它一次。奇怪!

<p>Click to copy</p>
<div id="container">
<div class="element">This is an element!</div>
</div>
$(document).ready(function () {
var obj = $(".element").clone(true);
$("p").click(function () {
//alert(obj); //Just to see if the variable is still an object.
$("#container").append(obj);
});
});

这是我的 CodePen 链接 http://codepen.io/anon/pen/Fwduf

这是我点击 5 次后得到的结果:

Click to copy

This is an element!
This is an element!

我应该看到的:

Click to copy

This is an element!
This is an element!
This is an element!
This is an element!
This is an element!
This is an element!

有趣的是,如果我在点击事件中移动可变减速,追加会完全按预期工作。

最佳答案

每次都需要克隆

Codepen Demo

$(document).ready(function () {
var obj = $(".element");
$("p").click(function () {
//alert(obj); //Just to see if the variable is still an object.
$("#container").append(obj.clone(true));
});
});

在你的例子中,你只创建了一次新的克隆元素,之后你只是将现有元素从一个地方移动到另一个地方

关于javascript - jQuery 不会 append 在文档就绪时声明的克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22172838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com