gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:34:15 27 4
gpt4 key购买 nike

我正在尝试根据初始选择从 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 来自初始选择,然后区域用于生成的选项。如果非常含糊,请道歉。

最佳答案

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

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

注意:

如果 JSON 正如您在问题中所指出的那样,您可以在使用它之前用几行代码对其进行调整。

关于javascript - 从外部 JSON 文件生成选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26593586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com