Jquery:获取祖先(或后代)和自身
人们可以使用 matchedset.find(selector)
/ matchedset.parents(selector)
来获取由选择器过滤的当前匹配集的后代/祖先,但这并没有t 包括匹配的集合本身(如果它也恰好与选择器匹配)。有没有比
matchedset.find(selector).add(matchedset.filter(selector))
和 各自的parents() 更好(更简洁和/或更快)的方法来获取它?
One can use matchedset.find(selector)
/ matchedset.parents(selector)
to get the descendants/ancestors of the current matched set filtered by a selector, but that doesn't include the matched set itself (if it happens to match the selector too). Is there a better (more concise and/or faster) way to get it than
matchedset.find(selector).add(matchedset.filter(selector))
and the respective for parents() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以这样做:
对于父母:
You can do this:
For parents:
我认为你的方法在执行时间方面是有效的,但你可能需要的是语法糖。为此,您可以将其包装到一个插件中:
然后像这样使用它:
如果您想变得更奇特,您可以创建一个插件,该插件不仅适用于“查找”,还适用于“父母”和“孩子”以及其他基于选择器的插件插件:
然后你将提供你想要调用的遍历插件作为第一个参数:
只是为了好玩,另一个有趣的插件,可以让你一次调用任意数量的遍历插件:
你可以使用选择器的任意组合来调用这个插件基于插件,如下:
I think your method is efficient in terms of execution time, but what you're probably asking for is syntactic sugar. For that, you could wrap it into a plugin:
Then use it like this:
If you wanted to get fancy you could create a plugin that works not only for 'find' but for 'parents' and 'children' and other selector-based plugins:
Then you'd supply as the first argument the traversal plugin you want to call:
Just for kicks, another fun plugin that lets you call an arbitrary number of traversal plugins all at once:
You could invoke this one with any combination of selector-based plugins, as follows:
虽然 Jeoff 的解决方案很好,但有时能够迭代所有元素(包括其本身而无需选择器)也很好。这个附加组件更加灵活:
While Jeoff's solution is nice, sometimes it's nice to be able to iterate all the elements, including itself without a selector. This add-on is a bit more flexible:
查找“andSelf()”函数。
Look up the "andSelf()" function.
对于父母,您有
最接近的(选择器)
For parents you have
closest(selector)