Select2 v4.0使optgroups可选 [英] Select2 v4.0 make optgroups selectable

查看:72
本文介绍了Select2 v4.0使optgroups可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是最新版本的select2(4.0.0),我找不到使optgroup可选的选项.

I'm using the latest version of select2 (4.0.0) and I can't find the option to make optgroups selectable.

optgroup用于对下拉菜单的不同选项进行分组,如其基本示例所示:

An optgroup is used to group different options of the dropdown, as shown in their basic examples:

我也需要这个optgoup才能选择!在3.5.1中是可能的,但现在不再是4.0.0中的默认设置.

I need this optgoup to be selectable too! It was possible in 3.5.1 but it isn't the default setting in 4.0.0 anymore.

我的代码如下:

$(document).ready(function() {
   $('#countrySelect').select2({
     data: [{
       text: "group",
       "id": 1,
       children: [{
         "text": "Test 2",
         "id": "2"
       }, {
         "text": "Test 3",
         "id": "3",
         "selected": true
       }]
     }]
   });
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />


<select id="countrySelect" style="width: 380px;" placeholder="Select regions..."></select>

推荐答案

这是已在GitHub上请求,但实际上实际上是不可能的.以前可以使用<input />,但是切换到<select>意味着我们现在

This was requested over on GitHub, but realistically it is not actually possible. It was previously possible with a <input />, but the switch to a <select> meant that we now explicitly disallow a selectable <optgroup>.

Select2可能永远无法解决这一技术障碍:无法在浏览器中选择标准<optgroup>.并且由于将具有children的数据对象转换为带有一组嵌套的<option>元素的<optgroup>,因此该问题同样适用于您的情况.

There is a technical barrier here that Select2 will likely never be able to tackle: A standard <optgroup> is not selectable in the browser. And because a data object with children is converted to an <optgroup> with a set of nested <option> elements, the problem applies in your case with the same issue.

最好的解决方案是具有<option>来选择组,就像使用标准选择.如果没有<option>标记,则无法将所选值设置为组(因为该值实际上不存在). Select2甚至具有templateResult选项(在3.x中为formatResult),因此您可以在浏览器中将其统一设置为一个组.

The best possible solution is to have an <option> for selecting the group, like you would have with a standard select. Without an <option> tag, it's not possible to set the selected value to the group (as the value doesn't actually exist). Select2 even has a templateResult option (formatResult in 3.x) so you can style it as a group consistently across browsers.

这篇关于Select2 v4.0使optgroups可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆