我正在使用Select2 3.5.2。尝试绑定到label
和value
而不是id
和的数组时text
,Select2自动完成功能不起作用。您能否让我知道我是否缺少任何选择?
jQuery(document).ready(function () {
var optionsList = [{value: 1, label: 'first'}, {value: 2, label: 'second'}, {value: 3, label: 'third'}, {value: 4, label: 'fourth'}];
$("#example_select2").select2({
data: optionsList,
dropdownAutoWidth: true,
id: 'value',
formatResult : function(item) { return item.label; },
formatSelection: function(item) { return item.label; }
});
});
</style><!-- Ugly Hack -->
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" />
<div id="example_select2"></div>
您看到的问题不是因为id
已更改,而是因为您正在使用label
而不是text
在数据对象中。Select2默认情况下会在text
对象的键上进行匹配,因此,如果不进行设置,它将无法找到任何东西,这是有道理的。
您可以通过将阵列数据更改为usetext
或将value
键重新映射到键来解决此问题text
。我也建议您对value
密钥进行此操作(使其成为id
),但这不是必需的,因为Select2 3.5.2支持该id
选项。Select2 4.0.0没有。
jQuery(document).ready(function () {
var optionsList = $.map(
[{value: 1, label: 'first'}, {value: 2, label: 'second'}, {value: 3, label: 'third'}, {value: 4, label: 'fourth'}],
function (obj) {
obj.id = obj.id || obj.value;
obj.text = obj.text || obj.label;
return obj;
});
$("#example_select2").select2({
data: optionsList,
dropdownAutoWidth: true
});
});
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" />
<input id="example_select2" type="text">
Select2还不支持附加到<div>
元素,因此我将其替换为对JavaScript禁用程度更高的<input type="text" />
元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句