【发布时间】:2021-10-28 18:39:14
【问题描述】:
我有一个带有 ajax 数据源的 select2 多选元素。我需要在加载时使用预选选项自动填充我的 select2。我按照说明in the docs 填充选项,这可以正常工作。但是,它似乎没有添加我传入的额外数据 - 它只有 ID 和文本。
这是我的代码的简化版本:
// create the option and append to Select2
let option = new Option('value', 'id', true, true);
$('#mySelect2').append(option).trigger('change');
// manually trigger the `select2:select` event; pass all data
let data = {
id: 'id',
text: 'value',
anotherId: 'anotherID',
moreData: 'moreData'
};
$('#mySelect2').trigger({
type: 'select2:select',
params: {
data: data
}
});
然而,当我尝试通过$('#mySelect2').select2('data') 访问选定的元素时,额外的属性(anotherId、moreData)不存在。我怎样才能传递额外的数据,以便它模仿用户实际从下拉列表中选择一个选项时发生的情况? (然后调用select2('data')时会显示额外的数据属性。)
【问题讨论】:
标签: jquery ajax jquery-select2