使用 select2 添加 "data-" 属性

Adding "data-" attributes with select2

我见过很多 Select2 选项标签设置 "data-" 属性的例子,我想这样做。

我正在使用 ajax 获取数据。我得到了构建 select 所需的 IDTEXT

But how can I add more attributes to it?

我只是没有找到添加它们的方法。

$(element).select2({
    placeholder: 'Select one...',
    width: '100%',
    minimumInputLength: 2,
    ajax: {
        url: '/my/url',
        dataType: 'json',
        data: function(params) {
            return {
                q: params.term,
                page: params.page
            };
         },
         processResults: function(data, page) {
             console.log(data);
             return {
                 results: data
             };
         },
         cache: true
     }
 });

我不确定你到底在问什么,但如果你想添加数据属性,你可以这样做..

在Jquery中:

$(element).attr('data-info', '222');

在javascript中:

document.getElementById('elementId').setAttribute('data',"value: 'someValue'");

此解决方案适用于 Select2 4.0 或更高版本。

假设您所谈论的属性已加载到您在 processResults 中返回的数组中。例如,如果您选择的记录类似于 ('id':1,'text':'some-text','custom_attribute':'hello world')

然后在更改事件中你可以这样做:

data=$("#selector").select2('data')[0];
console.log(data.custom_attribute);//displays hello world

希望对您有所帮助..

如果您对 ajax 电话的 JSON 回复如下所示:

[
  {
    "id": 1,
    "text": "option 1",
    "attr1": "custom attribute 1",
    "attr2": "custom attribute 2"
  },
  {
    "id": 2,
    "text": "option 2",
    "attr1": "custom attribute 3",
    "attr2": "custom attribute 4"
  }
]

然后,select2 似乎自动将它们添加为选项的数据属性,

这就是您访问它们的方式,例如 change 事件:

$(element).on('change', function(e) {
  console.log($(this).select2('data')[0]);
})

在上面的示例中,您现在可以访问您的 json 响应作为 select2('data') 属性。示例:$(this).select2('data')[0].attr1 将 return custom attribute 1

通过这种方式,我能够获取所选选项所需的数据 data-attribute。