【问题标题】:How to find the first ancestor of an element whose sibling is particular element in jquery?如何在jquery中找到其兄弟元素是特定元素的元素的第一个祖先?
【发布时间】:2016-09-28 15:28:08
【问题描述】:
<div>
  <input type="text">
  <span id="ending_point">
     <label>
        <span>
        <input type="text" id="starting_point">
           <span>
           </span>
        </span>
    </label>
  </span>
</div>

这里我想找到一个元素的祖先(这里有 id:starting_point),它的前一个兄弟是“input”。这里的答案是 span id 为“ending_point”,因为它的前一个兄弟是“input”。如何找到这个?

【问题讨论】:

    标签: jquery dom jquery-traversing


    【解决方案1】:

    您可以使用.parents.filter 的组合:

    var $ep = $("#starting_point")
      .parents()
      .filter(function() {
        return $(this).prev().is("input");
      })
      .first();
    
    // NB: the parents() method return all parents, CLOSEST ONE FIRST
    
    console.log($ep);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div>
      <input type="text">
      <span id="ending_point">
        <label>
          <span>
            <input type="text" id="starting_point">
            <span></span>
          </span>
        </label>
      </span>
    </div>

    【讨论】:

    • 这正是我想要的。谢谢 :)
    【解决方案2】:

    这是我的解决方案:

      $("input + span").first();
    

    这是您的选择器:$("input + span")。它选择他们在输入后立即跟随的所有跨度。使用 .first() 选择第一个。

    我为你创建了一个JSFiddle

    这里是Selectors Reference

    Greetz Eldo.ob

    【讨论】:

      【解决方案3】:

      如果您事先确切地知道层次结构,那么我会使用

      $( "#starting_point" ).parent().parent().parent().parent().find( "#ending_point" );
      

      或者用 .parentsUntil() (https://api.jquery.com/parentsUntil/) 做点什么。 (好吧,不是一个漂亮的解决方案,但肯定有效。)

      如果您不知道层次结构(它是动态创建的),但您确定 #starting_point 比 #ending_point“低”,那么您可以为此创建一个递归函数,检查您所在类型的每个级别正在寻找。

      // start_obj is the jQuery object you start your recursive function from
      // end_type is the type of element you are looking for in the hierarchy (e.g. input[ type="text" ] in your case
      
      function get_sibling_on_other_level( start_obj, end_type ) {
          var grampy = start_obj.parent().parent();
          if ( grampy.find( end_type ).length > 0 ) {
              return grampy.children( end_type );
          } else {
              // start the iteration "one level higher"
              // actually you should stop at "body" level - if you did not find
              // what you were looking for, then it's not in that branch of hierarchy
              get_sibling_on_other_level( start_obj.parent(), end_type );
          }
      }
      

      函数中使用的其他jQuery方法:https://api.jquery.com/children/

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-05
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        相关资源
        最近更新 更多