Javascript jQuery:在克隆的父级中查找克隆的子级?
假设我有一个jQuery扩展方法:Javascript jQuery:在克隆的父级中查找克隆的子级?,javascript,jquery,clone,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 =
$.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;
}
});
};
您无法在此处进行引用比较,因为
此
不在克隆中,它是原始元素,未移动。类似于您克隆的元素位于克隆的父元素中,因此您必须确定“相同”是什么意思,是相同的ID、相同的HTML内容还是相同的值
你只需要选择一个可以比较的值,因为这里的引用不起作用……你找不到不存在的东西:)你可以尝试给它一些唯一的类,可以用来引用回正确的元素
$.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");
};
进一步考虑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');
});
};
为什么不克隆父元素和当前元素?(此外,jQuery扩展中的
this
引用选择器选择的元素数组)。@Felix-如果您同时克隆了这两个元素,那么您将得到两个唯一的this
克隆。一个是直接克隆的,另一个是与父对象一起克隆的。@patrick dw:是的,这取决于OP实际想要做什么。。在中,每个()
,您不能执行这个.addClass
。和$('.someUniqueClass')。removeClass
不会从克隆中删除该类,因为它们还不是DOM的一部分。@patrick dw-很好,谢谢。我编辑了我的答案以反映它们。Ender-请记住,您处于.each()
循环中。因此,如果有50个元素,您将从DOM中选择$('.someUniqueClass')
50次,并添加克隆项并从所有元素中删除类50次。