>允许没有父级的 jQuery 子选择器吗?
简单的问题是,没有父级的 jQuery 子选择器 是否有效?如果是这样,你会如何使用它?
jQuery 子选择器的示例:
$('ul > li')
没有父级的 jQuery 子选择器的示例:
$('> li')
上面的第二个示例不起作用。但是我不记得我以前是否见过它,或者我见过类似的东西:
$('ul').not('>li')
也不起作用(但不会弹出错误消息,所以它只是被忽略?)
所以我的问题是你会曾经使用没有父选择器的子选择器,并且让它成为一个有效的 jQuery 选择器吗?
谢谢,抱歉,如果问题很愚蠢。 :)
编辑:
除了底部的 Nick 的 jQuery.find 示例之外,另一个用例是
$('ul:has(>li)')
注意: $('ul').has('>li') 是错误的,应该写为
$('ul').has('ul>li')
AND for not()
不确定如果我没说错的话,但你永远不会使用 >直接在 not() 内部,因为 not() 只关注一个元素,而 >比较多个元素。不过你可以做类似的事情
$('li:not(:has(>p))'
Quick question, is a jQuery child selector without a parent ever valid? If so, how would you use it?
Example of the jQuery child selector:
$('ul > li')
Example of jQuery child selector without parent:
$('> li')
The second example above doesn't work. However I can't remember if I saw it in the past before or I've seen something advance like:
$('ul').not('>li')
Doesn't really work either (but doesn't pop up an error message, so it's just ignored?)
So my question is would you EVER use a child selector without a parent, and have it be a valid jQuery selector.
Thanks, sorry if question is dumb. :)
Edit:
Along with Nick's jQuery.find example on the bottom, another use case is
$('ul:has(>li)')
Note: that $('ul').has('>li') is wrong and should be written
$('ul').has('ul>li')
AND for not()
Not sure if I have it correct, but you wouldn't ever use a > inside of not() directy because not() only concern about one element, while > compares multiple elements. However you can do something like
$('li:not(:has(>p))'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它可以在没有父级的情况下工作,但是它不能在默认上下文中,因为您的
不是< em>
直接
文档
的子级。另外,它本身没有任何意义,因为它是某物的直接子代,它与$("li")
相同。什么时候会用到呢?可能会减少代码,例如:
Yes it works without a parent, but it can't be on the default context, because your
<li>
isn't adirect
child of adocument
. Also, it wouldn't make any sense by itself really, since it's a direct child of something, it'd be the same as$("li")
.When would it be used? possibly to cut down on code, for example:
我无法想象需要没有父级选择器的子选择器的情况。子选择器用于选择父元素的直接子元素。如果没有父元素,应该选择谁的子元素?
I cannot think of a situation that requires a child selector without a parent. The child selector is used to select immediate children of a parent element. If there is no parent element, whose children should be selected?
你为什么想要那个?
你总是可以使用
$('* > li')
尽管我无法真正看到它会完成什么,因为li
应该始终是某些的子元素>ul
或ol
Why would you ever want that ?
You could always use
$('* > li')
although i can't really see what that would accomplish, asli
should always be a child of somethingul
orol