jQuery 中的后代选择器或自选择器
我想在 jQuery('.haystack')
返回的所有元素中搜索具有类 needle
的所有元素,并尝试过 jQuery('.haystack .needle' )
,但这似乎并不能解决一个元素同时具有两个类的情况。有没有一个选择器可以做到这一点?
I want to search for all elements with class needle
in all elements returned by jQuery('.haystack')
and have tried jQuery('.haystack .needle')
, but this doesn't seem to pick up the case where an element has both classes. Is there a selector that will do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试组合选择器:
这将选择所有
.haystack
还有.needle
和任何.needle
(它是.haystack
的后代),我认为这正是您所要求的:-)Try combining selectors:
This will select all
.haystack
s that are also.needle
s and any.needle
which is a descendant of a.haystack
, which I think is exactly what you asked for :-)您可以在其中没有空格的情况下执行此操作,如下所示:
另一种方法是:
使用空格来查找带有
.needle.haystack
元素的 子元素 code>,如果没有空格,您将匹配相同元素,但表示它们现在必须具有两个类才能匹配。这也是.filter()
所做的,它进一步减少了设置给这些元素的匹配项也与您传递给它的选择器匹配。You do this with no space in there, like this:
The alternative is:
With the space it's looking for children of those
.haystack
elements with.needle
, without the space, you're matching the same elements, but saying they must have both classes to match now. This is also what.filter()
does, it further cuts down the matches set to those elements also matching the selector you pass into it.