2014-07-13 2 views
1

저는 jQuery를 처음 사용하여 도움이 필요합니다. 내가 필요로 무엇addClass가 작동하지 않습니다 (jQuery)

<div class="first"> 
    Container 1 
    <div class="second hide"> 
     Some text 1 
     <div class="close">close</div> 
    </div> 
</div> 
<div class="first"> 
    Container 2 
    <div class="second hide"> 
     Some text 2 
     <div class="close">close 2</div> 
    </div> 
</div> 

그리고 jQuery를

$("div.first").click(function() { 
    $("div.first").find("div.second").addClass('hide'); 
    $(this).find("div.second").removeClass('hide'); 
}); 

$("div.close").click(function() { 
    $("div.close").parent().addClass('hide'); 
    $(this).parent().addClass('hide'); 
}); 

: 나는 여기에 HTML이 addClass

에 약간의 문제가 있습니다.

  1. 클릭 컨테이너 1.1 -> 쇼 컨테이너 1.2
  2. 클릭 컨테이너 2.1 -> 쇼 컨테이너 2.2 숨기 컨테이너 1.2
  3. 클릭 컨테이너 1.1 -> 쇼 컨테이너 1.2 숨기 컨테이너 2.2

위에 나열된 모든 것이 작동합니다.

이제 "닫기"를 클릭하면 모든 컨테이너 x.2를 숨길 필요가 있습니다. 나는 갈등이 있다고 생각하지만, 나는 어디 있는지 모른다.

여기에, 그렇지 않으면 당신은 다시 개방 사업부를 즉시 다음 닫기를 클릭하고있다, 당신은 close 버튼의 클릭 이벤트의 전파를 중지해야 http://jsfiddle.net/E69AN/2/

+0

show/hide 대신 jquery 메서드를 사용하십시오. $ (selector) .show() && $ (selector) .hide() 대신 – Runcorn

답변

3

입니다. 이 시도 : 당신이 .close 사업부를 클릭하면

$("div.first").click(function() { 
    $("div.second").addClass('hide'); 
    $(this).find("div.second").removeClass('hide'); 
}); 

$("div.close").click(function(e) { 
    e.stopPropagation(); 
    $(this).closest('.second').addClass('hide'); 
}); 

Updated fiddle

+0

대단히 감사합니다. – neorg

+0

@ user1817820 문제 없으니 기꺼이 도와주세요. –

2

것은,이 2 개 클릭 함수를 호출 이어질 것, 그것은 div.first 안에 있기 때문이다.

  1. 첫째는 div.first
  2. Immediatly 당신이 e.stopPropagation();하여이 동작을 방지 할 수 div.first

을 보여 이어질 것 $("div.first").click(fu...., 실행 숨길 이어질 것 $("div.close").click(fu....을 실행합니다

$("div.first").click(function() { 
    $(".second").hide(); 
    $(this).find(".second").show(); 
}); 

$("div.close").click(function(e) {  
    e.stopPropagation(); 
    $(this).parent().hide(); 
}); 

jsfiddle

관련 문제