Javascript 使用 select2 添加“data-”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33940477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding "data-" attributes with select2
提问by Victor Leal
I've seen a lot examples of Select2
option tags set with "data-" attributes and I would like to do it.
我已经看到很多Select2
使用“data-”属性设置选项标签的例子,我想这样做。
I'm using ajax to get the data. I get the ID
and the TEXT
needed to build the select.
我正在使用ajax来获取数据。我得到了ID
和TEXT
构建选择需要的。
But how can I add more attributes to it?
但是我怎样才能给它添加更多的属性呢?
I just didn't find the way to add them.
我只是没有找到添加它们的方法。
$(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
}
});
回答by Jeffrey - Humanized
This solution applies to Select2 versions 4.0 or higher.
此解决方案适用于 Select2 4.0 或更高版本。
Assuming the attributes your talking about are loaded in the array your returning in processResults. For example, if you are selecting a record like ('id':1,'text':'some-text','custom_attribute':'hello world')
假设您谈论的属性已加载到您在 processResults 中返回的数组中。例如,如果您选择像 ('id':1,'text':'some-text','custom_attribute':'hello world') 这样的记录
Then on a change event you can do:
然后在更改事件中,您可以执行以下操作:
data=$("#selector").select2('data')[0];
console.log(data.custom_attribute);//displays hello world
Hope it helps..
希望能帮助到你..
回答by Anand Singh
I am not sure what exactly you are asking but if you want to add data attribute you can do like this..
我不确定你到底在问什么,但如果你想添加数据属性,你可以这样做..
In Jquery:
在 Jquery 中:
$(element).attr('data-info', '222');
In javascript:
在 JavaScript 中:
document.getElementById('elementId').setAttribute('data',"value: 'someValue'");