jQuery clone infinite times?
The way jQuery's .clone()
seems to work, once you insert a cloned object somewhere, you cannot insert it again another time without re-cloning the original object. For example, if you do this:
var cloned = $('#elem1').clone();
$('#elem2').after(cloned);
$('#elem2').after(cloned);
Only one copy of elem1
will get copied and the second after
call would have done nothing.
Is t开发者_如何学Chere a way to not "clear the clipboard" after using a cloned object? Right now I am making do by cloning the object again before inserting it somewhere. Is there a better way to do this?
Your two lines just move the same jQuery set of elements twice. If you want a new copy yes you have to clone it again. after()
doesn't clone anything. It just moves content around. clone()
in this case is what's creating the content.
var cloned = $('#elem1').clone();
$('#elem2').after(cloned);
cloned = $('#elem1').clone();
$('#elem2').after(cloned);
Also you should change or remove the ID attribute when you do that:
var cloned = $('#elem1').clone().removeAttr("id");
$('#elem2').after(cloned);
cloned = $('#elem1').clone().removeAttr("id");
$('#elem2').after(cloned);
as duplicate IDs technically aren't allowed so behaviour is undefined.
精彩评论