2013-08-30 6 views
0

내가 드롭 다운 메뉴와 다양한 복잡성의 몇 div를 그릴 수있는 몇 가지 간단한 마크 업이 모두 표시 된 DIV 멀티 깊이를 숨기기 :jQuery를이 : 다음 중 하나

<select class='sel'> 
    <option data-opt='a'>show only 'a' boxes</option> 
    <option data-opt='b'>show only 'b' boxes</option> 
    <option data-opt='*'>show all</option> 
</select> 

<div class='holder'> 
    <div class='a'> 
     <div> 
      <p>Here is some text (A)</p> 
     </div> 
     <p>Plus more stuff in here.</p> 
    </div> 
    <div class='a'> 
     <p>More text (A)</p> 
    </div> 
    <div class='b'> 
     <p>Here is other text (B)</p> 
     <div><span>There is more in here!</span></div> 
    </div> 
    <div class='b'> 
     <p>Even more text (B)</p> 
    </div> 
</div> 

와 사용자가에서 옵션을 선택할 때

$('.sel').change(function() { 
    opt = $(this).find(":selected").data('opt'); 
    console.log('option chosen: '+opt); 

    if(opt == '*') { // select all 
     console.log('show all'); 
     $('.holder').show(); 

    } else { // hide all but this 
     $('.holder :not(div'+opt+')').hide(); 
     $('.holder').find('div'+opt).show(); 

    } 
}); 

그러나, 그것은 작동하지 않는 몇 가지 이유 : 드롭 다운, 나는 일치하지 않는 된 div 숨기기 만 일치 된 div 보여주고 싶어요. hide() 메서드는 모든 요소 (기본 DIV의 자식/형제 포함)를 숨기고있는 것처럼 보입니다. 그런 다음 show() 메서드는 초기 DIV 만 표시합니다. 그리고 show-all 옵션은 전혀 작동하지 않습니다. 그래서 깊이에 몇 가지 문제가 있습니다. 이 문제를 어떻게 해결할 수 있습니까?

는 JSFiddle : http://jsfiddle.net/pnoeric/FjEBY/3/

+0

당신은 내가 몰랐 : –

답변

1

http://jsfiddle.net/FjEBY/6/는 대답이다.

셀렉터가 약간 꺼져있어 opt 비트 전에 .을 잊어 버렸습니다. DOM 요소의 집합을 나타내는 jQuery를 객체 감안할 때

$('.sel').change(function() { 

    var opt = $(this).find(":selected").data('opt'), 
     all = $('.holder').children('div').show(); 

    if (opt !== '*') { 
     all.not('.' + opt).hide(); 
    } 

}); 
+0

내가 내 하나의 초를 조정할 필요가 사용하는 어떤 답을 선택하는 것을 잊지 마세요 상자 중 하나에 문장이 누락되었습니다. –

+0

걱정하지 마세요 ... 감사합니다! 거기에 아주 매끄러운 코드가 ... – Eric

+0

더 간단한 블록을 만들기 위해 Tushar와 광산을 결합했습니다. –

1

DEMO

$('.sel').change(function() { 
    opt = $(this).find(":selected").data('opt'); 
    console.log('option chosen: ' + opt); 
    if (opt == '*') { // select all 
     $('.holder').children('div').show() 
    } else { // hide all but this 
     $('.holder').children('div').show().not('.' + opt).hide(); 
    } 
}); 

.find() 방법은 우리가 DOM 트리에서 이러한 요소의 후손을 통해 검색하고 새의 jQuery 객체를 생성 할 수 있습니다 일치하는 요소에서 .find().children() 메서드는 비슷하지만 DOM 트리에서 단일 레벨로만 이동한다는 점만 다릅니다. 당신이 .children() 여기에 사용하는 경우

은 그래서 더 나은

DEMO

var holder = $('.holder').children('div'); 
$('.sel').change(function() { 
    opt = $(this).find(":selected").data('opt'); 
    console.log('option chosen: ' + opt); 
    if (opt == '*') { // select all 
     holder.show() 
    } else { // hide all but this 
     holder.show().not('.' + opt).hide(); 
    } 
}); 
+0

대단히 감사합니다! – Eric

+0

@Eric이 코드는 귀하의 것보다 빠릅니다. .find()'를 사용하고 있지만 목적은'.children()'과 함께 제공 될 수 있습니다.이 이미지 참조 -> http://tinyurl.com/2clyrbz –

+0

@ 문자 나는 짧은 코드 버전을 추가했습니다. –