克隆jQuery的原始

时间:2014-07-04 11:57:37

标签: javascript jquery

使用.clone()后有没有办法知道原始元素? 示例:

var clone = $("#foo").clone(false);
clone = clone.clone(false); //need it to work even if it's the clone of a clone
var foo = clone.original(); //this DOES NOT exist, but this is what i'd want. 
//foo is now $("#foo");

一个解决方案: 我认为我可以在数据字段中携带原始文件,但它非常重。

var source = $("#foo");
var clone = source.clone(false);
clone.data("id", source.getAttribute("id"));
var clone2 = clone.clone(false); //need it to work even if it's the clone of a clone
clone2.data("id", clone.data("id")); //here it's simplier that it would really be, because here I know, that it's already a clone that I'm cloning...
var foo = $("#"+clone2.data("id")); //foo is now $("#foo");

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

要从克隆对象获取原始对象,需要进行一些引用。只要有参考,GC就无法进行垃圾收集。这是没有引用原始对象的强烈理由。

为了您的目的,区分原件和重复;

var original = $('body');
var clone = original.clone(false);

检查选择器;

console.log(original.selector);
=> "body"


console.log(duplicate.selector);
=> ""

希望这会有所帮助。 :)

同样在克隆时,this就是jQuery所做的。

答案 1 :(得分:0)

这样做

$.fn.original = function(){
   return $(this).data('original');
};

$.fn.cloneO = function (deep){ 
   return $(this).clone(deep).data('original', $(this).original() ? $(this).original() : $(this)); 
};

然后你就可以克隆一个像cloneO一样的元素
var $clone = $('#foo').cloneO();
得到原来的样子
var $foo = $('#foo').cloneO().original();
或者  
var $foo = $('#foo').cloneO().cloneO().original();