2016-11-25 61 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. 如何在选择2上市的保留选项元素类? - 我在下面为那些对此感兴趣的人提供了一个答案。
  2. How to dynamically filter a select2 listing based on option class?我打开了一个新的问题线程,我回答这个问题的解决方案很不相同。

回答

1

我设法通过select2 plugin的模板功能来解决这个问题,

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

注意:这不会让你操纵选择2下拉列表中,因为类属性仅转移到内部自定义<span>我们项目的元素,而不是下拉select2列表的实际<li>元素。然而,它变得进一步风格的下拉列表,例如非常有用,

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

导致,

which makes for a nice visual distinction between different groups