2016-11-25 14 views
0

jquery select2ドロップダウンアイテムに要素クラスを転送することができるかどうかは誰にも分かりませんか?jquery select2ドロップダウンアイテムのオプションクラスを保持

<select> 
    <option class="group-1"></option> 
    <option class="group-1"></option> 
    <option class="group-2"></option> 
    <option class="group-2"></option> 
</select> 

ユーザーが選択「グループ1」、私は唯一のクラス「グループ-1」でアイテムを表示したいので、もし私が、別のドロップダウンからユーザが選択した値に基づいて動的リストを構築しようとしています。私は$('ul.select2 li.group-2').hide()のようなことをすることを望んでいた。

編集:私はこの問題を解決するために開発されてきた答えを明確にするため2にこの質問を分割しています、

  1. リストSELECT2にオプション要素のクラスを維持する方法は? - 私はこれに興味がある人のために以下の答えを提供しています。
  2. How to dynamically filter a select2 listing based on option class?私は新しい質問スレッドを開いていますが、私はこの質問に全く異なる解決策として答えています。

答えて

1

私はNOTE

<script type="text/javascript"> 
(function($) { 
    'use strict'; 

    var opportunities = $('select#opportunities').select2({ 
    dropdownParent: $('#select-opportunity'), 
    templateResult: formatItem 
    }); 
    function formatItem (state) { 
    if (!state.id) { return state.text; } 
    var $state = $(
     '<span class="opportunity-item ' + state.element.className + '">' + state.text + '</span>' 
    ); 
    return $state; 
    } 
})(jQuery); 
</script> 

select2 pluginのテンプレート機能を使用して、質問を解決するために管理:クラス属性のみに転送されるので、これはあなたがSELECT2のドロップダウンリストを操作することはできません。実際の <li>ドロップダウン選択2リストの要素ではなく、私たちの項目の内の <span>要素です。しかし、それは

which makes for a nice visual distinction between different groups

、その結果

<style> 
.opportunity-item.group-1::after{ 
    content: ''; 
    display: inline-block; 
    margin-left:5px; 
    width: 10px; 
    height: 10px; 
    -moz-border-radius: 10px; 
    -webkit-border-radius: 10px; 
    border-radius: 10px; 
    background-color: green; 
} 
.opportunity-item.group-2::after{ 
    content: ''; 
    display: inline-block; 
    margin-left:5px; 
    width: 10px; 
    height: 10px; 
    -moz-border-radius: 10px; 
    -webkit-border-radius: 10px; 
    border-radius: 10px; 
    background-color: blue; 
} 
</style> 

、例えば、ドロップダウンリスト、さらにスタイルに非常に便利になり

関連する問題