首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有头问题的jQuery-Select2数组

带有头问题的jQuery-Select2数组
EN

Stack Overflow用户
提问于 2016-05-20 17:58:45
回答 2查看 458关注 0票数 0

Select2:https://select2.github.io/

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

问题:它显示下拉列表,但所有选项都是对象。

代码语言:javascript
复制
$(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
            });
        });
    });

他们的建议数据格式

代码语言:javascript
复制
  {
  text: 'Group label',
  children: [
    {
      id: 'nested-1',
      text: 'First nested option'
    },
    // ... more data objects ...
  ]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-20 18:37:29

您将函数(属性)列表推送到attributeList数组,因此,为了获得适当的格式,您可以:

代码语言:javascript
复制
var properArray = [];

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

并将properArray传递给select2数据。

票数 0
EN

Stack Overflow用户

发布于 2016-05-20 18:40:44

试试这个

代码语言:javascript
复制
$(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
            });
        });
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37353043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档