jQuery: 在克隆的父元素中找到克隆的子元素?

3
假设我有这个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扩展中的this引用选择器选中的元素数组之外,为什么不克隆父元素和当前元素? - Felix Kling
@Felix - 如果你克隆了两者,那么你最终会得到两个唯一的this克隆体。一个是直接克隆的,另一个是随其父级一起克隆的。 - user113716
@patrick dw:没错,这取决于OP实际想要做什么... - Felix Kling
3个回答

3
你可以尝试给它添加一个独特的class,这样就可以用来引用到正确的元素。
$.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

进一步借鉴Patrick dw的答案,并结合Felix King的评论,我建议如下:

$.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');
    });
};

.each() 内部,你不能使用 this.addClass。而且 $('.someUniqueClass').removeClass 也无法从克隆体中移除类,因为它们还没有成为 DOM 的一部分。 - user113716
@patrick dw - 说得好,谢谢。我已经编辑了我的答案来反映它们。 - Ender
Ender - 请记住您正在一个 .each() 循环中。因此,如果有50个元素,则会从 DOM 中选择 $('.someUniqueClass') 50 次,并且将克隆的项目添加到所有这些元素中并删除它们的类名也会重复50次。 - user113716

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接