【问题标题】:Select2 json data not workingSelect2 json数据不起作用
【发布时间】:2016-05-02 02:41:46
【问题描述】:

当元素具有类“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);
            });

但结果很糟糕,它无法挂钩所有 select2 下拉列表

但是当我注释掉数据属性时,输出显示完美(但数据绑定丢失)

我的数组如下所示

[ { "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

【问题讨论】:

    标签: json select2


    【解决方案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/

    我认为您的数组数据有问题。请检查一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 2015-10-12
      • 2018-10-12
      • 2015-07-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      相关资源
      最近更新 更多