2010-09-02 60 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