如何在 Select2 中从数据源设置数据-*?

How to set data-* from datasources in Select2?

我使用 Select2 如下:

$('select#fields').select2({
   placeholder: 'Select a field',
   data: data.fields
});

data.fields 是这样的 JSON:

"fields": [
  {
    "id": "companies_id",
    "text": "companies_id",
    "data-type": "int"
  },
  {
    "id": "parent_companies_id",
    "text": "parent_companies_id",
    "data-type": "int"
  },
  {
    "id": "client_of_companies_id",
    "text": "client_of_companies_id",
    "data-type": "int"
  },
  {
    "id": "asset_locations_id",
    "text": "asset_locations_id",
    "data-type": "int"
  },
  {
    "id": "companies_name",
    "text": "companies_name",
    "data-type": "varchar"
  },
  {
    "id": "companies_number",
    "text": "companies_number",
    "data-type": "varchar"
  }
]

idtext用于填充选项值,我可以使用第三个值data-type并将其设置为<option>的属性吗?如果是这样怎么办?可以给我一个例子吗?

实际上 - 默认情况下,select2 将所有属性保存在它创建的 <option> 元素的 data('data') 变量中,您始终可以使用 $(<option>).data('data') 访问这些值,但是请记住,它与 data-type="value".data('type') 不同。您需要使用属性的完整名称。

这里是如何在 select 事件中获取 data-type 值的示例:

var $example = $("#s1").select2({
    data: [
        {
            "id": "companies_id",
            "text": "companies_id",
            "data-type": "int",
            "data-extra": '1'
        },
        {
            "id": "parent_companies_id",
            "text": "parent_companies_id",
            "data-type": "int",
            "data-extra": '2'
        },
        {
            "id": "client_of_companies_id",
            "text": "client_of_companies_id",
            "data-type": "int",
            "data-extra": '3'
        },
        {
            "id": "asset_locations_id",
            "text": "asset_locations_id",
            "data-type": "int",
            "data-extra": '4'
        },
        {
            "id": "companies_name",
            "text": "companies_name",
            "data-type": "varchar",
            "data-extra": '5'
        },
        {
            "id": "companies_number",
            "text": "companies_number",
            "data-type": "varchar",
            "data-extra": '6'
        }
    ],
}).on('select2:select', function(e) {
    console.log(e.params.data['data-type'], e.params.data['data-extra']);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<select id="s1">
</select>