0

我可以从服务返回任何 JSON。基于 JSON,我需要动态创建 SelectBox 并填写其中的值。

例如-

 JSON = {
    "Level": [{
        "Product": [{
            "ID": "ID1",
                "Brand": "Brand2",
                "Type": "Type3",
                "Line": "Line4",
                "Family": "Family5"
        }],
            "Location": [{
            "City": "City1",
                "State": "State2",
                "Region": "Region3",
                "Country": "Country4"
        }],
            "Time": [{
            "Day": "Day1",
                "Week": "Week2",
                "Month": "Month3",
                "Quarter": "Quarter4",
                "Year": "Year5"
        }]

    }]
} 

在这种情况下,将创建 3 个主选择框,其下有子选择框。Like - OneMain SelectBox - Time,Under time 5 个以上的选择框,Second SelectBox - Location,在这 4 个以上的选择框下等等。

我完全不知道如何使它动态到这样的水平。

4

2 回答 2

3

尝试这个,

var level=JSON['Level'][0];
for(var pr in level){
    var $select =$('<select/>');
    $select.append('<option>'+pr+'</option>');
    key=level[pr][0];
    for(k in key){
         $select.append('<option>'+key[k]+'</option>'); 
    }
    $select.appendTo('body');
}

现场演示

于 2014-04-02T06:12:46.847 回答
0

嗨,我认为这是您想要的示例,我正在使用 Jquery

var  JSONS = {
    "Level": [{
      "Product": [{
            "ID": "ID1",
                "Brand": "Brand2",
                "Type": "Type3",
                "Line": "Line4",
                "Family": "Family5"
        }],
            "Location": [{
            "City": "City1",
                "State": "State2",
                "Region": "Region3",
                "Country": "Country4"
        }],
            "Time": [{
            "Day": "Day1",
                "Week": "Week2",
                "Month": "Month3",
                "Quarter": "Quarter4",
                "Year": "Year5"
        }]

    }]
} 

$(document).ready(function(){
    $.each(JSONS.Level[0],function(key,val){
       var currentSection = val[0];

        var selectEle=$('<select id="'+key+'"></select>');
        $.each(currentSection,function(k,va){
          var op =  "<option>"+va+"</option>";
            selectEle.append(op);

        });

        $('#selectWrap').append(selectEle);        
    });



});
于 2014-04-02T06:17:18.470 回答