Javascript jquery仅克隆元素的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14178597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery clone only element's content
提问by Doua Beri
Is there a way in jQuery to clone an element's content? Not the entire element, only the content(children).
jQuery 中有没有办法克隆元素的内容?不是整个元素,只有内容(子元素)。
Something similar to what .html()is doing, but I'm also interested in cloning the events attached to the content.
类似于.html()正在做的事情,但我也对克隆附加到内容的事件感兴趣。
I was looking at .clone, but it seems that is cloning the entire element.
我在看.clone,但似乎是在克隆整个元素。
Thanks.
谢谢。
回答by Beetroot-Beetroot
Doua Beri, with reference to the jQuery API documentation for .clone()you will find that what you want is .clone(true,true). This will make a deep copy of an element (or a collection of elements), including all data and event bindings.
Doua Beri,参考jQuery API 文档,.clone()你会发现你想要的是.clone(true,true). 这将制作一个元素(或一组元素)的深层副本,包括所有数据和事件绑定。
You then have a choice of two options as to how you use .clone(true,true).
然后,您可以从两个选项中选择如何使用.clone(true,true).
Clone the children individually to give a jQuery collection comprising clones of the children.
var $childClones = $("#myElement").children().clone(true,true);Clone the outer element to give a jQuery collection comprising a clone of the outer element, itself containing clones of the children.
var $clone = $("#myElement").clone(true,true);
单独克隆子项以提供包含子项克隆的 jQuery 集合。
var $childClones = $("#myElement").children().clone(true,true);克隆外部元素以提供一个包含外部元素克隆的 jQuery 集合,该集合本身包含子元素的克隆。
var $clone = $("#myElement").clone(true,true);
It is somewhat academic which approach you adopt. In both cases the descendant elements are available collectively or individually to be manipulated and/or inserted into the DOM, though the code to do so would differ slightly.
你采用哪种方法有点学术。在这两种情况下,后代元素都可以集体或单独使用以进行操作和/或插入到 DOM 中,尽管这样做的代码会略有不同。
回答by nimrod
If you like a deep-copy just clone the children:
如果你喜欢深拷贝,只需克隆孩子:
$('#footer-flair').children().clone()
$('#footer-flair').children().clone()
And instead of attaching events to particular elements attach an event to a container element that is listening to child elements, that way your events will fire as long as the container element stays even if you add/remove a thousand elements inside the container. You could do this on the body tag if you never want your events to go away.
并且不是将事件附加到特定元素,而是将事件附加到正在侦听子元素的容器元素,这样只要容器元素保持不变,即使您在容器内添加/删除一千个元素,您的事件也会触发。如果您不想让事件消失,您可以在 body 标签上执行此操作。
Use the 'on' method to bind events like so:
使用 'on' 方法绑定事件,如下所示:
$('body').on('click', 'button.className', function(){
alert('button clicked');
});

