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;
}
});
};
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;
}
});
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试给它一些独特的类,可用于引用正确的元素。
You could try giving it some unique class that could be used to refer back to the proper element.
您无法在此处进行参考比较,因为
this
不在克隆中,它是原始元素,未移动。与您克隆的元素类似的元素位于克隆的父元素中,因此您必须确定“相同”意味着什么,它是相同的 ID、相同的 HTML 内容还是相同的值吗?您只需要选择一个可以比较的值,因为引用在这里不起作用......您找不到不存在的东西:)
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 :)
进一步考虑 patrick dw 的答案,并结合 Felix King 的评论,我建议如下:
Taking patrick dw's answer a little further, and incorporating Felix King's comment, I would suggest the following: