【发布时间】:2019-02-26 12:28:55
【问题描述】:
我需要使用 templateResult 格式化 select2 上的结果。
<select id="example" style="width:400px">
<optgroup data-anag="Month" data-col1="Col1" data-col2="Col2">
<option data-anag="January" data-col1="jan1" data-col2="jan2" value="JAN">January</option>
<option data-anag="February" data-col1="feb1" data-col2="feb2" value="FEB">February</option>
<option data-anag="March" data-col1="mar1" data-col2="mar2" value="MAR">March</option>
<option data-anag="April" data-col1="apr1" data-col2="apr2" value="APR">April</option>
</optgroup>
</select>
<select id="example2" style="width:400px">
</select>
function formatRes(data) {
var month = $(data.element).data('anag');
var c1 = $(data.element).data('col1');
var c2 = $(data.element).data('col2');
var $result = $(
'<div class="row">' +
'<div class="col-md-4 col-xs-4">' + month + '</div>' +
'<div class="col-md-2 col-xs-2">' + c1 + '</div>' +
'<div class="col-md-2 col-xs-2">' + c2 + '</div>' +
'</div>'
);
return $result;
}
// NON AJAX VERSION: WORK GREAT
$('#example').select2({
templateResult: formatRes
});
//AJAX VERSION: DOESN'T WORK
var jsonresp = '[ {"id":"1", "name": "January", "col1":"jan1", "col2":"jan2"}, {"id":"2", "name": "February", "col1":"feb1", "col2":"feb2"}, {"id":"3", "name": "March", "col1":"mar1", "col2":"mar2"}, {"id":"4", "name": "April", "col1":"apr1", "col2":"apr2"}]';
$("#example2").select2({
templateResult: formatRes,
ajax: {
url: "/echo/json/",
delay: 500,
dataType: 'json',
params: {contentType: "application/json"},
data: function(term, page){
//Code for dummy ajax response
return {
json: jsonresp,
delay: 0
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id,
col1: item.col1,
col2: item.col2
}
})
};
}
}
});
我需要在我的小提琴中从示例 (1) 到示例 (2) 构建相同的结果:
https://jsfiddle.net/sdejLqkx/2/
但是使用带有 ajax 的版本我不知道如何编辑它以获得与示例 (1) 相同的结果结构:
- 带有 optgroup 附件
- 在 ajax 版本中使用 templateResult
编辑:我有一些改进。现在我使用 ajax 在响应中获得列,但我不知道如何添加 optgroup 附件。 https://jsfiddle.net/sdejLqkx/3/
【问题讨论】:
标签: jquery jquery-select2