2013-08-30 104 views
0

我有一些簡單的標記畫一個下拉菜單和不同複雜程度的幾個div的:jQuery的:隱藏多深的所有div,然後顯示一個

<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> 

而當用戶選擇從一個選項下拉,我想隱藏不匹配的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(); 

    } 
}); 

但是,由於某種原因,它不工作。它看起來像hide()方法隱藏每個元素(包括主DIV的子/兄弟),然後show()方法只顯示初始DIV。而顯示全部選項根本不起作用。所以有一些深度問題。我怎樣才能解決這個問題?

的jsfiddle:http://jsfiddle.net/pnoeric/FjEBY/3/

+0

不要忘了挑你用什麼:) –

回答

1

http://jsfiddle.net/FjEBY/6/就是答案。

您的選擇器有點不對,您忘記opt位之前的.

$('.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

聯合圖沙爾和我的一個更簡單的塊 –

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(); 
    } 
}); 

如果提供的jQuery代表了一組DOM元素,該.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

@eric我添加了更短版本的代碼。 –