2016-05-02 105 views
0

我想钩一个元素时有一个类“select2picker”我也定制,如果下拉列表的来源是一个数组。我下面Select2 JSON数据不工作

$('.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); 
      }); 

但结果代码是可怕的失败挂钩的所有选择2下拉列表 enter image description here

但是当我注释掉数据属性,输出显示完美(但数据绑定就不复存在了) enter image description here

我的阵列看起来像下面

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

我对发生了什么问题感到困惑。任何想法?

选择二版本:3.4.8

回答

1

此行给出了一个错误:var jsonValue = JSON.parse($(this).attr('data-json')).val());

应该是:var jsonValue = JSON.parse($(this).attr('data-json'));

而且这条线在你的问题:

i am also customising if the source of the dropdown list is an array

表示,我认为这也可能是一个数组。在这个原因中,你应该检查它是否是一个数组,然后再将数据传递给select2。

编辑:我想到的另一件事是以下。 如果您使用的数据属性的占位符,我不认为你需要像你这样在这里

placeholder: $(this).attr('data-placeholder'), 
minimumInputLength: $(this).attr('data-minimumInputLength'), 

可能是你需要选择一个通过这些属性的值来选择2第二次这两个(或者在你的设置中传递它,或者使用一个属性)。由于select2查看数据属性以获取值。

我检查,如果上述是正确的事实证明它不是。它工作正常,在这种提琴:https://jsfiddle.net/wL7oxbpv/

我觉得有什么不对您的阵列数据。请检查。