2011-03-31 2 views
0

jQuery가 제대로 작동하는 데 문제가 있습니다. 나는이 HTML 구조가 있습니다jquery closest() tree traversal

<div class="hide"><!-- form --></div> 
<div class="button-hide"><a href="#">Hide Form</a></div> 
<div class="button-show"><a href="#">Show Form</a></div> 

'버튼 쇼'앵커를 클릭하면 위의 버튼 숨기기 '사업부를 보여, 그것은 자신 사업부의 숨기고 위의'숨기기 '를 전환해야을 div에 :

$(document).ready(function(){ 

$(".hide").hide(); 
$(".button-hide").hide(); 

$("div.button-show a").click(function(){ 
    $(this).closest("div.hide").slideToggle(); 
    $(this).closest("div.button-hide").show(); 
    $(this).hide(); 
}); 
}); 

이 중 아무 것도 작동하지 않습니다. 여기 'nearest()'명령을 잘못 사용하고 있습니까?

답변

0

부모 div가 아닌 링크에서 가장 가까운 부분이 일치합니다. . 부모()와 비슷해야합니다. closest()

0

부모님()처럼 조상이 가장 근접합니다. 위의 div는 조상은 아니지만 형제 (alex 's answer)입니다. 다른 사람에서 JQuery와의 다음

<div class="parent-container"> 
    <div class="hide"><!-- form --></div> 
    <div class="button-hide"><a href="#">Hide Form</a></div> 
    <div class="button-show"><a href="#">Show Form</a></div> 
</div> 

$(".button-show a").click(function(){ 
    $(this).parents(".parent-container").find(".button-hide").show(); 
    etc 
}) 
3

조금 다른 ...

: 당신은 그 div의 그것보다 그냥 이런 기준으로 그것을 사용하기위한 컨테이너 사업부가 있다면
$(".button-show a").click(function(){ 
    $(this).parent().siblings(".button-hide").show(); 
    ... 
}); 
+0

이들은 형제가 아닙니다. – Mark

+1

@ Mark는 닌자 업데이트를 참조하십시오.}} – alex

+0

Ah gotcha. 그때 작동합니다. :) – Mark