【问题标题】:Preserve option class in jquery select2 dropdown items在 jquery select2 下拉项中保留选项类
【发布时间】:2016-11-25 14:39:52
【问题描述】:
有人知道是否可以将元素类转移到 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 个,
- 如何在 select2 列表中保留选项元素类? - 我在下面为对此感兴趣的人提供答案。
-
How to dynamically filter a select2 listing based on option class?我打开了一个新的问题线程,我在其中回答这个问题,因为解决方案完全不同。
【问题讨论】:
标签:
jquery-select2
jquery-select2-4
【解决方案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>
注意:这不允许您操作 select2 下拉列表,因为 class 属性仅传输到我们项目的内部自定义 <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>
导致,