Javascript 克隆jQuery的原始版本
在使用.clone()之后,有没有办法知道原始元素? 例如:Javascript 克隆jQuery的原始版本,javascript,jquery,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 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");
有什么建议吗?要从克隆对象中获取原始对象,它需要有一些参考。只要存在引用,GC就不能对其进行垃圾收集。这是不引用原始对象的有力理由 为了您的目的,区分原件和副本
var original = $('body');
var clone = original.clone(false);
检查选择器
console.log(original.selector);
=> "body"
console.log(duplicate.selector);
=> ""
希望这有帮助。:)
同样,在克隆时,jQuery也会这样做。这样就可以了
$.fn.original = function(){
return $(this).data('original');
};
$.fn.cloneO = function (deep){
return $(this).clone(deep).data('original', $(this).original() ? $(this).original() : $(this));
};
然后,您将能够使用cloneO-like克隆元素
var$clone=$('#foo').cloneO()代码>
然后像这样得到原作
var$foo=$('#foo').cloneO().original()代码>
或与
var$foo=$('#foo').cloneO().cloneO().original()代码>一个额外的ID是否很重?!真的吗?对于您的信息,您没有将clone
和clone2
添加到DOM中,即使添加了,也会导致无效的HTML,除非您更改它们的ID。因此,原始文件仍然是DOM中唯一的**文件,并且是将由$(“#foo')
选择的文件。您需要知道这一点有什么用?请注意,一个文档中的ID必须是唯一的,顺便说一句。@AdrianoRepetti我克隆了很多,我不太喜欢在这些字段中携带数据。@bergi我在mysql中存储一些数据的副本,因为我知道,我无法比较两个克隆是否具有相同的来源。选择器不推荐使用吗?我不明白这是怎么回事。我想只使用克隆对象访问原始对象。@Richard是的,它已被弃用。这不起作用-您已将.original
属性添加到jQuery对象(这是暂时的),而不是新元素本身。@Alnitak:您是对的。当克隆附加到html中,并且为该元素创建了一个“新”jQuery对象时,原始函数将不可用。但是,上面的代码与描述的用例相匹配。为了使此解决方案更通用,可以在$.fn命名空间中定义原始函数/属性。