2014-07-04 3 views
0

.clone()을 사용한 후에 원래 요소를 알 수있는 방법이 있습니까? 예 :원본 클론 jQuery

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"); 

의견이 있으십니까?

+0

이 하나와 같은 원본을 얻을 것이다 여분의 ID는 꽤 무거워?! 정말? –

+0

여러분의 정보를 위해서'clone'과'clone2'를 모두 DOM에 추가하지 않았고 그렇게했다하더라도 ID를 변경하지 않으면 무효 HTML로 이어질 것입니다. 따라서 원본은 여전히 ​​DOM에있는 유일한 하나이며'$ ('# foo') '에 의해 선택됩니다. – PeterKA

+2

무엇을 알아야합니까? 한 문서의 ID는 고유해야하며 btw 여야합니다. – Bergi

답변

0

이는

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

그런 다음
var $clone = $('#foo').cloneO();
같은 cloneO와 요소를 복제 할 수있을 것입니다 수행하고
var $foo = $('#foo').cloneO().original();
또는 var $foo = $('#foo').cloneO().cloneO().original();

+0

이것은 작동하지 않습니다.'.original' 속성을 jQuery 객체 (일시적입니다)에 추가했지만 새로운 요소 자체에는 추가하지 않았습니다. – Alnitak

+0

그것은 까다 롭습니다 : o. 해야 할 일, 고마워. – Richard

0

복제 된 개체에서 원본 개체를 얻으려면 몇 가지 참조가 필요합니다. 참조가있는 한 GC는 가비지 수집을 할 수 없습니다. 원본 개체에 대한 참조가없는 강력한 이유입니다.

원본을 복제본과 구별하기 위해,

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

선택기를 확인하십시오.

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


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

희망이 있습니다. :)

또한 복제 할 때 this은 jQuery의 기능입니다.

+0

은 .selector가 지원되지 않습니다. 어떻게 작동하는지 이해할 수 없습니다. 복제 된 객체 만 사용하여 원본에 액세스 할 수 있어야합니다. – Richard

+0

@ 리차드 예, 사용 중지되었습니다. – Alnitak