是否有人知道是否可以将元素类传递到jquery下拉项目?
<select>
<option class="group-1"></option>
<option class="group-1"></option>
<option class="group-2"></option>
<option class="group-2"></option>
</select>我试图根据用户从另一个下拉列表中选择的值构建一个动态列表,因此如果用户选择'group 1‘,那么我希望只显示类'group-1’的项。我希望能做一些像$('ul.select2 li.group-2').hide()这样的事情。
编辑:为了解决这个问题,我把这个问题分成两个部分来回答,
发布于 2016-11-28 13:13:38
通过使用select2插件的模板功能,我设法解决了这个问题,
<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>结果,

https://stackoverflow.com/questions/40807362
复制相似问题