繁体   English   中英

jQuery-具有标头问题的Select2数组

[英]Jquery - Select2 array with header Issue

Select2: https//select2.github.io/

最终结果应类似于https://select2.github.io/examples.html示例多个选择框。

问题:显示下拉列表,但所有选项均为Object对象。

在此处输入图片说明

$(document).ready(function () {
        function attribute(text) {
            this.text = text;
            this.children = [];
            this.addChild = function (tid, tvalue) {
                var val = { id: tid, text: tvalue };
                this.children.push(val);
            }
        }
        $.get("/products/attributelist", function (data) {
            var attributeList = [];
            $.each(data.AttributeGroups, function (i, val) {
                var tmpAttr = new attribute(val.Name);
                $.each(val.Attributes, function (val1) {
                    tmpAttr.addChild(val1.Id, val1.Name);
                });
                attributeList.push(tmpAttr);
            });
            $(".js-example-basic-multiple").select2({
                data: attributeList
            });
        });
    });

他们的建议数据格式

  {
  text: 'Group label',
  children: [
    {
      id: 'nested-1',
      text: 'First nested option'
    },
    // ... more data objects ...
  ]
}

您将功能列表(属性)推送到attributeList数组,因此对于正确的格式,您可以:

var properArray = [];

for (var i = 0; i< attributeList.length; i++) {
  properArray.push({text: attributeList[i].text, children: attributeList[i].children})
}

并传递propertyArray到select2数据

试试这个

$(document).ready(function () {
        function attribute(text) {
            return {
                text:text,
                children:[],
                addChild : function (tid, tvalue) {
                    var val = { id: tid, text: tvalue };
                    this.children.push(val);
                }
            }
        }
        $.get("/products/attributelist", function (data) {
            var attributeList = [];
            $.each(data.AttributeGroups, function (i, val) {
                var tmpAttr = attribute(val.Name);
                $.each(val.Attributes, function (val1) {
                    tmpAttr.addChild(val1.Id, val1.Name);
                });
                attributeList.push(tmpAttr);
            });
            $(".js-example-basic-multiple").select2({
                data: attributeList
            });
        });
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM