jquery:children() vs 子选择器">"
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5750583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: children() vs child selector ">"
提问by user417918
I have a table that has a section similar to the following:
我有一个表,其中有一个类似于以下的部分:
<tr>
<td> <span class="myclass"></span>
</td>
<tr>
my $(this) is set to the tr element and I'm trying to access the Span elements that have the "myclass" class set. The following seems to work:
我的 $(this) 设置为 tr 元素,我正在尝试访问设置了“myclass”类的 Span 元素。以下似乎有效:
if ($(this).children('td').children('span').is('.myclass')){
alert('in here');
}
but when trying to use this:
但是当尝试使用它时:
if ($(this).children("td > span").is('.myclass')){
or this:
或这个:
if ($(this).children("td span").is('.myclass')){
It does not. I thought that either of the above 2 would come up with similar results (albeit through different methods) but apparently not.
它不是。我认为上述 2 中的任何一个都会得出类似的结果(尽管通过不同的方法),但显然不是。
What am I missing here?
我在这里缺少什么?
Thanks!
谢谢!
回答by Felix Kling
children(selector)
will only match those children that match selector
. None of tr
's children (the td
s) can match td > span
, as tr
has has no span
child elements, only td
s and td > span !== td
.
children(selector)
只会匹配那些匹配的孩子selector
。的子元素tr
(td
s)都不能匹配td > span
,因为tr
has 没有span
子元素,只有td
s 和td > span !== td
。
The documentationis also quite clear about this:
该文件也是关于这个相当明确:
Get the children of each element in the set of matched elements, optionally filtered by a selector.
获取匹配元素集中每个元素的子元素,可选择由选择器过滤。
What you might want instead is .find()
:
你可能想要的是.find()
:
$(this).find("td > span")
It returns all descendants, not just children, that match the selector.
它返回与选择器匹配的所有后代,而不仅仅是孩子。
回答by Kevin Ennis
From the jQuery docs:
来自 jQuery 文档:
"The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree."
“.find() 和 .children() 方法是相似的,除了后者只在 DOM 树中向下移动一个级别。”
I'd recommend using this:
我建议使用这个:
if ($(this).find('.myclass').length){
alert('in here');
}
Cheers
干杯
回答by SLaks
I explained this here.
The difference is that the first selector is entirely within the children
call, whereas the second one isn't.
不同之处在于第一个选择器完全在children
调用中,而第二个不在调用中。
Therefore, the first one looks for all children of this
which also match td > span
. (In other words, all {<span>
s children of <td>
s }(the selector) that are themselves directly children of this
)
因此,第一个会查找所有this
也匹配的孩子td > span
。(换句话说,所有{<span>
s 的子<td>
s }(选择器)本身就是 的直接子this
)
The second one will find all <td>
children of this
, then find all of the <span>
s in those <td>
s.
第二个将找到 的所有<td>
孩子this
,然后找到<span>
那些<td>
s中的所有s。