当一个元素有类“select2picker”时,我试图挂钩select2如果下拉列表的源是一个数组,我也在自定义。我的代码在下面
$('.select2picker').each(function() {
var settings = {};
if ($(this).attr('data-json')) {
var jsonValue = JSON.parse($(this).attr('data-json')).val());
settings = {
placeholder: $(this).attr('data-placeholder'),
minimumInputLength: $(this).attr('data-minimumInputLength'),
allowClear: true,
data: jsonValue
}
}
$(this).select2(settings);
});
但是当我注释掉data属性时,输出显示完美(但数据绑定丢失了)
我的数组如下所示
[ { "id": "2015-0152", "text": "2015-0152" }, { "id": "2015-0153", "text": "2015-0153" }, { "id": "2016-0001", "text": "2016-0001" }, { "id": "2016-0002", "text": "2016-0002" }, { "id": "2016-0003", "text": "2016-0003" }, { "id": "2016-0004", "text": "2016-0004" }, { "id": "2016-0005", "text": "2016-0005" }, { "id": "2016-0006", "text": "2016-0006" }, { "id": "2016-0007", "text": "2016-0007" }, { ... }, { "id": "2015-0100", "text": "2015-0100" }, { "id": "2015-0101", "text": "2015-0101" }, { "id": "2015-0080", "text": "2015-0080" }, { "id": "2015-0081", "text": "2015-0081" }, { "id": "2015-0090", "text": "2015-0090" }, { "id": "2015-0102", "text": "2015-0102" }, { "id": "2015-0112", "text": "2015-0112" }, { "id": "2015-0128", "text": "2015-0128" }, { "id": "2015-0136", "text": "2015-0136" } ]
我对出了什么问题感到很困惑。有什么想法吗?
Select2版本:3.4.8
答案 0 :(得分:1)
此行显示错误:var jsonValue = JSON.parse($(this).attr('data-json')).val());
应该是:var jsonValue = JSON.parse($(this).attr('data-json'));
。
您问题中的这一行:
如果下拉列表的来源是数组
,我也在自定义
向我表明它可能不是一个数组。在这种情况下,您应该在将数据传递给select2之前检查它是否是一个数组。
编辑:我想到的另一件事是以下内容。 如果您正在使用占位符的数据属性,我认为您不需要像这样第二次将这些属性的值传递给select2
placeholder: $(this).attr('data-placeholder'),
minimumInputLength: $(this).attr('data-minimumInputLength'),
您可能需要选择其中一个(在您的设置中传递它,或使用属性)。当select2查看数据属性以获取值时。
我检查了上面的内容是否正确结果不是。它在这个小提琴中工作得很好:https://jsfiddle.net/wL7oxbpv/
我认为您的阵列数据存在问题。请检查一下。