【问题标题】:Getting to the correct children找到正确的孩子
【发布时间】:2014-12-23 08:20:31
【问题描述】:

如果我有以下代码块,请说

<div id='demo'>
    <div class='ui-demo first'>
        <p></p>
    </div>
    <div class='ui-demo second'>
        <p></p>
    </div>
<div>

使用“ui-demo second”类访问div下的“p”标签是否正确?

$('#demo').find('.ui-demo second').find('p')

或者这条线也可以吗?

$('#demo').children('.ui-demo second').find('p')

我尝试了 console.log 两者,但我不确定它是否工作。我想在 p 标签内附加一个列表,但仅适用于第二个孩子的 p,而不是第一个。

谢谢

【问题讨论】:

  • 为什么不只是$('#demo').find('.ui-demo.second &gt; p')

标签: jquery jquery-selectors children


【解决方案1】:

不应该有空格:

$('#demo .ui-demo.second').find('p')

$('#demo').find('.second p')

除此之外,您也可以使用它:

$('#demo .ui-demo:first').next('div').find('p')

【讨论】:

  • 哦,空间就是问题所在。感谢您指出这一点。顺便说一句,在使用 find() 时是否需要列出该 div 中的每个类,或者如果我想将其用作参考,则只列出其中的一部分?
【解决方案2】:

你应该试试,

$('#demo').find('.ui-demo.second').find('p');
// no space -------------^ in both the classes, as second is not ui-demo's child

或使用单个find() 喜欢,

$('#demo').find('.ui-demo.second p');

阅读hierarchy-selectors 了解其工作原理。

【讨论】:

    【解决方案3】:

    如果您使用find('.ui-demo second'),您将尝试获取一个不存在的元素&lt;second&gt;,它是.ui-demo 元素的子元素。 而是使用:

    $('#demo').find('.ui-demo.second').find('p')
    

    选择同样具有.second 类的.ui-demo 元素

    【讨论】:

      【解决方案4】:
      $('.ui-demo.second > p').text("some data for paragraph");
      

      Demo

      既然你想附加一个列表,你可以这样做

      $('.ui-demo.second > p').append("<ul><li>1</li><li>2</li></ul>");
      

      Demo 2

      如果您还有其他一些与上面使用的类名相同的元素,那么请尝试更具体地使用您的选择器。查看其他人的答案,他们从 #demo 开始选择,但如果您确定您的 HTML 页面中没有其他具有此类名称的类,那么我提供的解决方案就足够了,更少的计算。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2014-08-12
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        相关资源
        最近更新 更多