从外部JSON文件生成选择列表

时间:2014-10-27 17:45:02

标签: javascript jquery json select

我正在尝试根据初始选择从JSON文件生成选择菜单。我已经看到了很多不同的方式,人们为此编写了一个功能,但想要的东西非常简单。

HTML:

<select class="form-control" id="beta-filter1" data-set="default" data-select="practise">
    <option label="Please select" value="">Please select</option>
    <option label="Practise one" value="Practise one">Practise one</option>
    <option label="Practise two" value="Practise three">Practise two</option>
    <option label="Practise three" value="Practise three">Practise three</option>
</select>
<select class="form-control" id="beta-filter2" data-set="default" data-select="law" disabled>
    <option label="Please select" value="">Please select</option>
</select>

JSON:

[
  {
    "Practise one": [
        {"area": "Acquisition and Leveraged Finance"},
        {"area": "Asset-Based Lending"},
        {"area": "Bankruptcy"}
    ]
  },
  {
    "Practise two": [
        {"area": "Corporate Governence"},
        {"area": "Derivatives"},
        {"area": "High Yield Offerings"}
    ]
  },
  {
    "Practise three": [
        {"area": "Electric Power Regulation"},
        {"area": "Export Control"},
        {"area": "FCPA"}
    ]
  }
]

我想使用外部JSON文件中的数据。练习1/2/3来自初始选择,然后区域用于生成的选项。抱歉,如果非常模糊。

1 个答案:

答案 0 :(得分:1)

我从您的JSON中删除了一些冗余,以尝试进一步简化您的代码。例如,您可以将{"area": "Electric Power Regulation"}更改为"Electric Power Regulation",然后将{text:this.area,value:this.area}更改为{text:this,value:this},就可以进一步简化它。

&#13;
&#13;
var options = {
    "Practise one": [
        {"area": "Acquisition and Leveraged Finance"},
        {"area": "Asset-Based Lending"},
        {"area": "Bankruptcy"}
    ],
    "Practise two": [
        {"area": "Corporate Governence"},
        {"area": "Derivatives"},
        {"area": "High Yield Offerings"}
    ],
    "Practise three": [
        {"area": "Electric Power Regulation"},
        {"area": "Export Control"},
        {"area": "FCPA"}
    ]
  },
    sel1 = $('#beta-filter1'),
    sel2 = $('#beta-filter2');

sel1.on('change', function() {
  $('option:gt(0)', sel2).remove();
  sel2.prop('disabled', true);
  if( this.selectedIndex > 0 ) {
    $.each( options[this.value], function() {
      sel2.append( $('<option/>',{text:this.area,value:this.area}) ).prop('disabled', false);
    });
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="beta-filter1" data-set="default" data-select="practise">
    <option label="Please select" value="">Please select</option>
    <option label="Practise one" value="Practise one">Practise one</option>
    <option label="Practise two" value="Practise two">Practise two</option>
    <option label="Practise three" value="Practise three">Practise three</option>
</select>
<select class="form-control" id="beta-filter2" data-set="default" data-select="law" disabled>
    <option label="Please select" value="">Please select</option>
</select>
&#13;
&#13;
&#13;

注意

如果您在问题中指出了JSON,则可以在使用之前用几行代码进行调整。