我见过很多使用“data-”属性设置的 Select2
选项标签的例子,我想这样做。
我正在使用 ajax 获取数据。我得到构建选择所需的 ID
和 TEXT
。
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
}
});
最佳答案
此解决方案适用于 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
希望对你有帮助..
关于javascript - 使用 select2 添加 "data-"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940477/