有两种方法可以通过编程方式访问当前选择的数据:使用.select2('data')
,或者使用 jQuery 选择器。
data
方法调用select2('data')
将返回一个 JavaScript 对象数组,表示当前的选择。每个对象将包含源数据对象传入时所具有的所有属性/值。processResults
和templateResult
回调函数。
$('#mySelect2').select2('data');
也可以通过:selected
jQuery 选择器访问已选项:
$('#mySelect2').find(':selected');
可以扩展<option>
表示当前选择的元素,并通过 HTMLdata-*
属性来包含源数据对象中的任意数据:
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
不要依赖
selected
的属性<option>
元素来确定当前选中的项目。当从远程数据源创建元素时,Select2 不会添加selected
属性。此问题以获得更多信息。