开发者

jQuery: Finding cloned child in cloned parent?

开发者 https://www.devze.com 2023-01-14 12:32 出处:网络
Let\'s say I have this jQuery extension method: $.fn.foobar = function() { var clone = this.parent().clone();

Let's say I have this jQuery extension method:

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

After I've gotten clone, how can I find the cloned child element that is the same as this?

Will this work?

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

Or 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;
        }
    });
};


You could try giving it some unique class that could be used to refer back to the proper element.

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


You can't get a reference comparison to work here because this isn't in the clone, it's the original element, it wasn't moved. An element like the one you cloned is in the cloned parent, so you have to decide what "the same" means, is it the same ID, the same HTML content, the same value?

You just need to pick a value you can compare, because the reference won't work here...you can't find something that isn't there :)


Taking patrick dw's answer a little further, and incorporating Felix King's comment, I would suggest the following:

$.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

精彩评论

暂无评论...
验证码 换一张
取 消