可通过创建一个新的 Javascript 对象,然后将其追加到控件中,从而以编程方式向 Select2 控件添加新选项:JavaScriptOption
对象并将其追加到控件中:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
第三个参数new Option(...)
决定该项目是否“默认被选中”;也就是说,它会设置新选项的selected
属性。第四个参数设置选项的实际选中状态——如果设置为true
,则新选项将默认被选中。
您可以使用.find
如果该选项已经存在就选择它,否则创建它:
// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
$('#mySelect2').val(data.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data.text, data.id, true, true);
// Append it to the select
$('#mySelect2').append(newOption).trigger('change');
}
要以编程方式为 Select2 控件选择一个选项/条目,请使用 jQuery 的.val()
方法:
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
您也可以传递一个数组给val
进行多项选择:
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
Select2 会监听绑定在其上的change
事件。<select>
元素。当您进行任何需要在 Select2 中反映的外部更改时(例如更改值),应触发此事件。
对于从AJAX 数据源获取数据的 Select2 控件来说,.val()
的方法不起作用。因为选项还不存在,AJAX 请求只有在打开控件和/或用户开始搜索时才会触发。再加上服务器端的过滤和分页功能,这使得特定条目何时实际加载进 Select2 控件变得不确定!
因此,解决这个问题的最佳办法就是简单地将预选条目作为新选项添加进去。对于远程数据源的情况,可能需要在您的服务端应用程序中创建一个能够检索单个项目的 API 端点:
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
请注意我们手动触发了select2:select
事件,并且传入了完整的data
对象。这让其他处理程序能够访问所选项的额外属性.
您可以通过将 Select2 控件的值设为null
:
$('#mySelect2').val(null).trigger('change');