代码之家  ›  专栏  ›  技术社区  ›  Cheeso

jquery:如何选择我父母的所有p子代?

  •  5
  • Cheeso  · 技术社区  · 15 年前

    HTML:

    <style>
       hidden { display:none;}
    </style>
    
    <div id="div1">
      <a href="#" onclick="expandSiblingParagraphs(this)">+</a>
      <p>Hello</p>
      <p class="hidden">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. 
        Integer vulputate, nibh non rhoncus euismod, erat odio pellentesque lacus, 
        sit amet convallis mi augue et odio. Phasellus cursus urna facilisis quam.
        Suspendisse nec.</p>
      <p class="hidden">Another hidden paragraph</p>
    </div>
    

    我正在尝试的javascript:

    var expandSiblingParagraphs = function(elt){
      $(this).parent()....?
    };
    

    我要选择所有属于被单击元素父级的子级的p,并从中移除隐藏类。在逻辑中,我不想假设包含DIV的ID,甚至不想假设包含DIV的ID。我只希望父容器的所有P子容器。

    我该怎么做?

    the selector syntax 我可以找到一种方法来获得后代或孩子。我找不到选择父母或提升者的方法。我错过什么了吗? 谢谢。

    2 回复  |  直到 15 年前
        1
  •  16
  •   TStamper    15 年前
    $(this).parent().children("p.hidden").removeClass("hidden");
    
        2
  •  0
  •   Mike Robinson    15 年前

    我喜欢使用closest,因为它会冒泡:

    $(this).closest("div").find("p").show()
    

    或考虑:

    $(this).siblings("p").show();
    

    [更新] 基于以下评论和其他答案:

    $(this).siblings("p.hidden").removeClass("hidden");