【问题标题】:How to filter out option tags from the original select with Select2?如何使用 Select2 从原始选择中过滤掉选项标签?
【发布时间】:2013-03-16 01:27:30
【问题描述】:
似乎是一个非常简单的想法,但我不知道如何从 select2 下拉列表中过滤掉原始选择的选项标签。
基本上是这样的:
<select id="select">
<option class="car">Car 1</option>
<option class="plane">Plane 1</option>
</select>
$("#select").select2();
... 应该创建一个仅带有 car 类的选项标签的假选择。
【问题讨论】:
标签:
javascript
jquery
jquery-select2
【解决方案2】:
只是为了让这个问题保持最新。使用提供 matcher 函数的建议答案已过时。从 Select2 4.0.0 开始,您需要 use a wrapper 和 matcher:
function matchStart (term, text) {
if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
return true;
}
return false;
}
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
$(".js-example-matcher-start").select2({
matcher: oldMatcher(matchStart)
})
});
对我来说,这行不通。我不知道为什么。但是我找到了解决方法。显然,使用 Select2 您还可以为选择中的每个 option 或元素提供格式函数到 .select2() 方法。例如,当您想在每个元素前面加上一个图标或类似的东西。事实证明,如果您在格式函数中返回 null,则该元素将不会显示在下拉列表中,如下所示:
function formatState(state) {
if (!state.id) { return state.text; }
if (state.disabled) { return null; }
var $state = $('<span>'.concat(state.text).concat("</span>"));
return $state;
}
$('#myDropdown').select2({
templateResult: formatState
});
这立即对我有用。也许它可以帮助你们中的任何人使用当前的实现。
【解决方案3】:
您应该使用该选项的“禁用”属性。如果要过滤掉它,请将其设置为“禁用”。这在 select2 中将其变灰。或者,您可以使用 CSS 类将其隐藏而不是变灰。
【解决方案4】:
一段时间以来,我一直在努力解决问题,并发布了我自己的类似question。上面提供的匹配器解决方案的问题在于,匹配器用于匹配搜索,而仅打开下拉列表只会匹配所有列表,因此会显示不太令人满意的所有内容。
在最初的错误solution 之后,我终于求助于“销毁”select2 并在过滤选择后重建它。这是使用这种方法解决问题的方法,
//assuming you are usign jquery...
//keep a non-filtered copy of the original select
var $clonedSelect = $('select#select').clone();
$.fn.filterSelect2 = function(class=''){
if( $(this).is('select') ){
$(this).select2('destroy');
$(this).empty();
$(this).append( $('option.'+class, $clonedSelect).clone() );
$(this).select2();
}
return $(this);
}
$('select#select').filterSelect2('car'); //will create a select2 with only the car class options.
我没有对此进行测试,但我在最近的一个项目中对一个更复杂的案例使用了类似的逻辑,发现它工作得非常好。