【问题标题】:Creating dynamic SelectBoxs based on JSON using jquery使用 jquery 创建基于 JSON 的动态选择框
【发布时间】:2014-04-02 05:58:53
【问题描述】:

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

例如-

 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 个选择框, 第二个选择框 - 位置,在另外 4 个选择框下等等。

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

【问题讨论】:

    标签: javascript jquery json jquery-selectbox


    【解决方案1】:

    试试这个,

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

    Live Demo

    【讨论】:

      【解决方案2】:

      嗨,我认为这就是你想要的 example,我正在使用 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);        
          });
      
      
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        相关资源
        最近更新 更多