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

使用jquery获取附近的div子元素

  •  1
  • onlinepch  · 技术社区  · 11 年前

    如何使用jquery获取附近div的子元素? 我正在尝试验证()我需要获取的输入元素 class=grand_child_02 ,当我进来时 class=input_01

    HTML格式:

    <div class="parent">
        <div class="child_01">
          <h4 class="grand_child_01_01">
            <a href="#" class="link_01">link_01</a>
          </h4>
          <div class="grand_child_01_02">Some_text</div>
       </div>
       <div class="child_02">
         <div class="grand_child_02_01">
           <input type="text" class="input_01"/>
         </div>
       </div>
      </div>  
    

    谢谢

    3 回复  |  直到 11 年前
        1
  •  3
  •   Felix    11 年前

    您可以使用 closest() , siblings() find() :

    var grand_child_02 = $(this).closest('.child_02').siblings('.child_01').find('.grand_child_02');
    

    具有 $(this) 提到 .input_01 要素

        2
  •  2
  •   Milind Anantwar    11 年前

    使用:

    $(this).closest('.child_02').siblings('div').find('.grand_child_02')
    

    Working Fiddle

        3
  •  1
  •   iCollect.it Ltd    11 年前

    为了澄清我的意见:

    我对其他两个答案都投了赞成票,认为是正确的,但我建议只使用 siblings() 没有过滤器。

    var $target = $(this).closest('.child_02').siblings().find('.grand_child_02');
    

    哪里 this 是您指定的输入元素。

    如果您只使用siblings(),它将与其他添加的兄弟div元素一起工作(在实际情况中可能会发生这种情况)。我认为这对更改更为稳健(并且比使用同级过滤器慢得多)。

    例如在该示例中:

    小提琴: http://jsfiddle.net/TrueBlueAussie/tw3Yc/1/