[英]Adding "data-" attributes with select2
我已经看到很多使用“data-”属性设置Select2
选项标签的例子,我想这样做。
我正在使用ajax来获取数据。 我得到了构建选择所需的ID
和TEXT
。
但是我怎样才能给它添加更多的属性呢?
我只是没有找到添加它们的方法。
$(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
}
});
此解决方案适用于 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
希望能帮助到你..
我不确定你到底在问什么,但如果你想添加数据属性,你可以这样做..
在 Jquery 中:
$(element).attr('data-info', '222');
在 JavaScript 中:
document.getElementById('elementId').setAttribute('data',"value: 'someValue'");
如果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]);
})
在上面的示例中,您现在可以作为 select2('data') 属性访问您的 json 响应。 示例: $(this).select2('data')[0].attr1
将返回custom attribute 1
通过这种方式,我能够获取所选选项所需的数据属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.