2017-05-28 19 views
0

如果只有一個元素(<tr>)具有該類,但是如果存在多個元素則全部隱藏,以下jQuery代碼僅用於顯示選定選項與班級。需要改變什麼?jQuery,切換大小寫以顯示同一類中的多個選定選項

$(document).ready(function() { 
 
    $("#genre").change(function() { 
 
    var id = $(this).find("option:selected").attr("id"); 
 
    switch (id) { 
 
     case "opt_all": 
 
     $("tr").show(); 
 
     break; 
 
     case "opt_family": 
 
     $(".family").show().siblings().hide(); 
 
     break; 
 
     case "opt_life": 
 
     $(".lifestyle").show().siblings().hide(); 
 
     break; 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select name='genre' id='genre'> 
 
     <option id='opt_all' selected='selected'>All Genre</option> 
 
     <option id='opt_family'>Family &amp; Friends</option>     
 
     <option id='opt_life'>Lifestyle</option>  
 
    </select> 
 
<table> 
 
    <tr class="family"></tr> 
 
    <tr class="life"></tr> 
 
    <tr class="family"></tr> 
 
</table>

+0

因爲'兄弟姐妹()'拿起任何同級元素時,沒有兄弟姐妹叫,甚至是那些在原始選擇器中(哪個'siblings()'不知道))。你可能想刪除所有'.siblings(':not(.lifestyle)')'例如。或者倒轉它並先做隱藏,然後顯示。這可能更容易。 –

+0

像這樣:https://jsfiddle.net/kd07q3bb/ vs this:https://jsfiddle.net/kd07q3bb/1/ –

+0

謝謝你的建議!添加':not(.__)'的作品!你讓我今天一整天都感覺很好。 @Jared Farrish – isosmall

回答

0

最簡單的方法是扭轉它:隱藏,然後顯示。

$(document).ready(function() { 
    $("#genre").change(function() { 
    var id = $(this).find("option:selected").attr("id"); 
    switch (id) { 
     case "opt_all": 
     $(this).show(); 
     break; 
     case "opt_family": 
     $('.tr').hide().filter(".family").show(); 
     break; 
     case "opt_life": 
     $('.tr').hide().filter(".lifestyle").show(); 
     break; 
    } 
    }); 
}); 

或者否定它的siblings()濾波器選擇,所以你排除你剛剛操作了什麼上:

$(document).ready(function() { 
    $("#genre").change(function() { 
    var id = $(this).find("option:selected").attr("id"); 
    switch (id) { 
     case "opt_all": 
     $("tr").show(); 
     break; 
     case "opt_family": 
     $(".family").show().siblings(':not(.family)').hide(); 
     break; 
     case "opt_life": 
     $(".lifestyle").show().siblings(':not(.lifetyle)').hide(); 
     break; 
    } 
    }); 
}); 
-1

可以使用。每次用相同的選擇要素:

$(".family").each(function(index,element){ 
    element.hide(); 
}) 
+0

這是完全不必要的,並不能解決問題。 –

+0

謝謝!我將不得不嘗試這個。它看起來更有效。 – isosmall