jQueryparents() - 单独处理每一层
当我有一个匹配多个元素的类时,有没有一种方法可以单独处理每一层父级,
$(".myWidespreadClass").parents() // [immediateParent1, immediateParent2, deeperAncestor1, deeperAncestor2]
我希望能够运行类似 .each() 的东西,但是第一次迭代运行在直接父级上,第二次迭代运行在更深的祖先上下一个级别等等...
When I have a class that matches several elements is there a way to process each tier of parents inidividually
$(".myWidespreadClass").parents() // [immediateParent1, immediateParent2, deeperAncestor1, deeperAncestor2]
I would like to be able to run something like .each() but where the first iteration runs over immediate parents, the second over deeper ancestors at the next level etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有趣的问题。我想你会想要一个循环,像这样:
Live example | 实时源 - 更新,但请参阅下文,这可能会提前终止
您可能想早点终止,例如:...取决于您的需要。我在示例中做到了。见下文。更新实际上,您必须小心提前终止,可能在处理父母时最好进行过滤,如下所示:
实例 | 实时源
原因是您的初始元素集可能位于 DOM 中截然不同的级别,因此对于其中一些元素,您将比其他元素更快到达最顶层元素。上面的
body
检查可能不适合您的需求,但您明白了。Fascinating question. I think you'll want a loop, something like this:
Live example | Live source - Update but see below, that could terminate early
You may want to terminate a bit earlier than that, e.g.:...depending on your needs. I did in the example.See below.Update Actually, you have to be careful with the early termination, probably better off filtering when you're processing the parents instead, something like this:
Live example | Live source
The reason being that your initial set of elements may be at wildly different levels in the DOM, and so you'll reach the topmost element for some of them sooner than for others. The
body
check above may not be appropriate for your needs, but you get the idea.