2017-05-28 13 views
0

次のjQueryコードは、そのクラスに1つの要素(<tr>)しかない場合、選択されたオプションのみを表示するように機能しますが、クラスと一緒に。変更する必要があるものは何ですか?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/対この: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

あなたが同じセレクタを持つ要素に対して.each使用することができます。

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

これはまったく必要ではなく、問題を解決しません。 –

+0

ありがとうございました!私はこれを試さなければならないでしょう。それはより効率的な方法のように見えます。 – isosmall

関連する問題