jQuery clone infinite times?

寵の児 提交于 2019-12-08 13:35:17

问题


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 there 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?


回答1:


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.



来源:https://stackoverflow.com/questions/2264167/jquery-clone-infinite-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!