>没有父级的jQuery子级选择器? [英] > jQuery Child Selector without a parent allowed?

查看:110
本文介绍了>没有父级的jQuery子级选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,没有父级的 jQuery子选择器是否有效?如果是这样,您将如何使用它?

Quick question, is a jQuery child selector without a parent ever valid? If so, how would you use it?

jQuery子选择器的示例:

Example of the jQuery child selector:

$('ul > li')

没有父级的jQuery子级选择器示例:

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?)

所以我的问题是,您是否会永远使用没有父项的子项选择器,并使其成为有效的jQuery选择器.

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. :)

底部还有Nick的jQuery.find示例,另一个用例是

Along with Nick's jQuery.find example on the bottom, another use case is

$('ul:has(>li)')

注意:$('ul').has('> li')是错误的,应写为

Note: that $('ul').has('>li') is wrong and should be written

$('ul').has('ul>li')


与非()


AND for not()

不确定我是否正确,但是您永远不会在not()内部直接使用>,因为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))'

推荐答案

是的,它在没有父级的情况下也可以工作,不能在 default 上下文中使用,因为您的<li>不是document direct 子级.另外,它本身并没有任何意义,因为它是某物的直接子代,因此它与$("li")相同.

Yes it works without a parent, but it can't be on the default context, because your <li> isn't a direct child of a document. 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:

$(this).find("> li > span a");
//as opposed to not being able to start with it:
$(this).children("li").children("span").find("a");

这篇关于&gt;没有父级的jQuery子级选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆