2016-09-28 1 views
0
<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) 이전 형제가 "입력"이기 때문에 응답은 id가 "ending_point"인 스팬입니다 .How 이것을 찾으려면? $("input + span") : 이것은 당신의 선택은형제가 jquery의 특정 요소 인 요소의 첫 번째 조상을 찾는 방법은 무엇입니까?

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

입니다 :

답변

0

당신은 .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>

+0

이 내가 당신을 want.Thank 정확히 :) – AmudhaVigneshwaran

0

여기 내 솔루션입니다. 입력 후 일시적으로 따라 오는 모든 범위를 선택합니다. 그리고 .first()를 사용하여 첫 번째 것을 선택하십시오.

나는 JSFiddle을 생성했습니다.

그리고 여기가 Selectors Reference

Greetz Eldo.ob입니다

0

을 사전에 다음을 사용합니다.

$("#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/

관련 문제