获取已选内容

有两种方法可以通过编程方式访问当前选择的数据:使用.select2('data'),或者使用 jQuery 选择器。

使用data方法

调用select2('data')将返回一个 JavaScript 对象数组,表示当前的选择。每个对象将包含源数据对象传入时所具有的所有属性/值。processResultstemplateResult回调函数。

$('#mySelect2').select2('data');

使用 jQuery 选择器

也可以通过:selectedjQuery 选择器访问已选项:

$('#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属性。此问题以获得更多信息。

无噪 Logo
无噪文档
25 年 6 月翻译
文档源↗