2010-09-02 121 views
3

比方說,我有這樣的jQuery的擴展方法:jQuery:在克隆父項中查找克隆的子項?

$.fn.foobar = function() { 
    var clone = this.parent().clone(); 
}; 

我已經得到clone後,我怎麼能找到克隆子元素是一樣的this

這項工作?

$.fn.foobar = function() { 
    var clone = this.parent().clone(); 
    var cloneOfThis = clone.find(this); 
}; 

還是這個?

$.fn.foobar = function() { 
    var clone = this.parent().clone(); 
    var self = this; 
    var cloneOfThis; 
    clone.children().each(function() { 
     var $this = $(this); 
     if ($this === self) { 
      cloneOfThis = $this; 
     } 
    }); 
}; 
+1

爲什麼不能克隆家長和當前元素? (除了''這個jQuery擴展中的''是指選擇器選擇的元素數組。 – 2010-09-02 21:48:19

+0

@Felix - 看起來,如果你克隆了兩者,那麼你最終會得到2個'this'的獨特克隆。一個直接克隆,一個與父母一起克隆。 – user113716 2010-09-02 22:04:35

+0

@patrick dw:真的,這取決於OP實際想要做什麼...... – 2010-09-02 22:11:01

回答

3

你可以嘗試給它一些獨特的類可以用來引用回適當的元素。

$.fn.foobar = function() { 
     // Add a class to "this", then clone its parent 
    var clonedParent = this.addClass("someUniqueClass").parent().clone(); 
     // Reference the new clone of "this" inside the cloned parent, 
     // then remove the class 
    var cloneOfThis = clonedParent.find(".someUniqueClass").removeClass("someUniqueClass"); 
     // Remove the class from the original 
    this.removeClass("someUniqueClass"); 
}; 
1

你不能得到一個參考比較,在這裏工作,因爲this不是克隆,這是原始的元素,它沒有移動。一個元素您克隆的元素位於克隆的父級,因此您必須決定「相同」意味着什麼,它是相同的ID,相同的HTML內容,相同的值?

你只需要選擇一個值,你可以比較,因爲引用不會在這裏工作...你找不到的東西,是不是有:)

0

以帕特里克DW的回答遠一點,並納入菲利克斯國王的意見,我建議如下:

$.fn.foobar = function() { 
    return $(this).each(function() { 
     // Add a class to "this", then clone its parent 
     var clonedParent = $(this).addClass("someUniqueClass").parent().clone(); 

     // Reference the new clone of "this" inside the cloned parent 
     var cloneOfThis = clonedParent.find(".someUniqueClass"); 

     //remove the unique class to preserve the original state (other than the clone which is now present) 
     $('.someUniqueClass').add(cloneOfThis).removeClass('someUniqueClass'); 
    }); 
}; 
+0

在'.each()'裏面,你不能執行'this.addClass'。而'$('。someUniqueClass')。removeClass'不會從克隆中移除類,因爲它們還不是DOM的一部分。 – user113716 2010-09-02 22:09:55

+0

@patrick dw - 好點,謝謝。我編輯了我的答案以反映它們。 – Ender 2010-09-02 22:23:59

+0

Ender - 請記住你在'.each()'循環中。因此,如果有50個元素,您將從DOM中選擇$('。someUniqueClass')'50次,並添加克隆的項目並將其從所有項目中移除50次。 – user113716 2010-09-02 22:27:02