所以这是一个有趣的情况,我还没有找到任何解决方案,我想知道这是否可能。我想要一个无限滚动(分页)的 select2 框,但我希望能够对结果进行分组。我知道的一件事是,我不需要将数据插入到我尚未完成的组中。这是一个用例:
将显示按年龄组排序的用户的 select2 框。我有一个 12-18 岁的年龄段,我只想一次拉回 10 个用户。如何将这些用户添加到 12-18 岁年龄段?
最佳答案
您没有为您的问题添加示例代码,所以我提供了一个通用的解决方案。
首先,您必须创建一个包含子元素的 json
答案,并且您必须按组对其进行排序。这意味着Group1不能在答案中的Group2之后再来。
第一页:
{
"items": [
{
"text": "Group1",
"children": [
{
"id": 1123,
"text": "opt 1/1"
},
{
"id": 1234,
"text": "opt 1/2"
},
{
"id": 1345,
"text": "opt 1/3"
}
]
}
],
"total": 963
}
第二页
{
"items": [
{
"text": "Group1",
"children": [
{
"id": 1456,
"text": "opt 1/4"
},
{
"id": 1567,
"text": "opt 1/5"
}
]
},
{
"text": "Group2",
"children": [
{
"id": 2123,
"text": "opt 2/1"
}
]
}
],
"total": 963
}
第三页
{
"items": [
{
"text": "Group2",
"children": [
{
"id": 2234,
"text": "opt 2/2"
},
{
"id": 2345,
"text": "opt 2/3"
},
{
"id": 2456,
"text": "opt 2/4"
}
]
}
],
"total": 963
}
其次,您需要从下拉列表中删除重复的 optgroups。
可以使用 templateResult 选项自定义下拉列表中搜索结果的外观(选项和选项组)。我通过此选项删除了重复的 optgroups 和标签。
$(document).ready(function() {
$('#mySelect2').select2({
templateResult: formatOptions,
ajax: {
url: 'https://api.github.com/search/repositories',
data: function (params) {
// Query parameters will be ?search=[term]&page=[page]
return {
search: params.term,
page: params.page || 1
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * self.options.limit) < data.total
}
};
}
}
});
function formatOptions(item, container, $el) {
// optgroups section
if (item.children && item.children.length > 0) {
// don't format the repeated optgroups!
if ($(".select2-results__group").text() === item.text) {
return;
}
if ($('[aria-label="' + item.text + '"]').length > 0) {
return;
}
// the first occasion of the given optgroup
return $el;
}
// options section
// here you can implement your own logic if you want to customise the output of the options
$el.addClass('something-special-result result');
return $el;
}
});
https://stackoverflow.com/questions/23642603/