javascript - jQuery:在克隆的 parent 中寻找克隆的 child ?

标签 javascript jquery clone

假设我有这个 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;
        }
    });
};

最佳答案

你可以尝试给它一些独特的类,可以用来引用正确的元素。

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

关于javascript - jQuery:在克隆的 parent 中寻找克隆的 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631536/

相关文章:

Chrome 和 Internet Explorer 中的 javascript 数组

javascript - 克隆的 div 未正确保留在网格中

javascript - 每次点击添加按钮添加一个

java - 在 Java 中克隆一个对象需要什么

java - Java 中泛型的深拷贝

javascript - 需要在多个 Div 框 onClick 上使用函数

javascript - 如果缺少元素,则 jQuery 错误

javascript - 我需要创建一个简单的数据库以用于 Angular/Node 演示。将此类数据库添加到我的演示中的阻力最小的路径是什么?

javascript - 如何使用jquery清除点击按钮的效果

jquery - 使用自定义宽高,jQuery Mobile Dialog center to screen