【问题标题】:jquery: children() vs child selector ">"jquery:children() vs 子选择器">"
【发布时间】:2011-08-10 16:06:21
【问题描述】:

我有一个表,其部分类似于以下内容:

<tr>
    <td> <span class="myclass"></span>
    </td>
<tr>

我的 $(this) 设置为 tr 元素,我正在尝试访问设置了“myclass”类的 Span 元素。 以下似乎有效:

if ($(this).children('td').children('span').is('.myclass')){
    alert('in here');
}

但是当尝试使用这个时:

if ($(this).children("td > span").is('.myclass')){

或者这个:

if ($(this).children("td span").is('.myclass')){

它没有。我认为上述两种方法中的任何一种都会得出相似的结果(尽管通过不同的方法),但显然不是。

我在这里错过了什么?

谢谢!

【问题讨论】:

    标签: jquery jquery-selectors children


    【解决方案1】:

    children(selector) 只会匹配那些匹配selector 的孩子。 tr 的所有子元素(tds)都不能匹配td &gt; span,因为tr 没有span 子元素,只有tds 和td &gt; span !== td。

    documentation对此也很清楚:

    获取匹配元素集中每个元素的子元素,可选地由选择器过滤。


    你可能想要的是.find():

    $(this).find("td > span")
    

    它返回匹配选择器的所有后代,而不仅仅是孩子。

    【讨论】:

      【解决方案2】:

      我解释了这个here。

      不同之处在于第一个选择器完全在 children 调用中,而第二个不是。

      因此,第一个查找this 的所有子代也匹配td &gt; span。 (换句话说,&lt;td&gt;s }(选择器)的所有 { &lt;span&gt;s 子节点本身就是 this 的子节点)

      第二个将找到this 的所有&lt;td&gt; 子代,然后在这些&lt;td&gt;s 中找到所有&lt;span&gt;s。

      【讨论】:

        【解决方案3】:

        来自 jQuery 文档:

        “.find() 和 .children() 方法是相似的,只是后者只沿着 DOM 树向下移动一层。”

        我建议使用这个:

        if ($(this).find('.myclass').length){
            alert('in here');
        }
        

        干杯

        【讨论】:

          猜你喜欢
          • 2013-10-18
          • 1970-01-01
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 2015-06-27
          • 1970-01-01
          相关资源
          最近更新 更多