[英]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.