gpt4 book ai didi

javascript - jQuery 和 JSON : chained select from an array with multiple values

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:40 25 4
gpt4 key购买 nike

我有一个 JSON 文件 (json/cities.json),它以下列形式将我国各州与其城市相关联:

{
"State #1": [
"City #1 from State #1",
"City #2 from State #1",
"City #3 from State #1"
],
"State #2": [
"City #1 from State #2",
"City #2 from State #2",
"City #3 from State #2"
]
}

我还有一个带有状态的 HTML 选择,如下所示:

<select id="state" name="state">
<option value="State #1"> State #1 </option>
<option value="State #2"> State #2 </option>
</select>

和一个空的 HTML 城市选择:

<select id="city" name="city"></select>

我想做的是用按键(州)过滤的 JSON 值填充城市的 HTML 选择。

我正在使用以下 jQuery 脚本:

$('#state').on('change', function () {
var state = $(this).val(), city = $('#city');
$.getJSON('json/cities.json', function (result) {
$.each(result, function (i, value) {
if (i === state) {
var obj = city.append($("<option></option>").attr("value", value).text(value));
console.log(obj);
}
});
});
});

问题是当 console.log 返回以下标记时,本应填充城市的选择甚至没有改变:

<select name="city" id="city">
<option value="City #1 form State #1, City #2 from State #1, City #3 from State #1">
City #1 from State #1, City #2 from State #1, City #3 from State #1
</option>
</select>

也就是说,值作为一个值返回,而它应该是多个值(每个值用逗号分隔)。

最佳答案

您正在遍历各州而不是城市。 result[state] 为您提供迭代的城市数组。

附言代码中的 url 部分只是为了让它在代码段中工作

$('#state').on('change', function () {
var state = $(this).val(), city = $('#city');
city.empty();
var url = URL.createObjectURL(new Blob(['{"State #1":["City #1 from State #1","City #2 from State #1","City #3 from State #1"],"State #2":["City #1 from State #2","City #2 from State #2","City #3 from State #2"]}'], {type:'application/json'}));
$.getJSON(url, function (result) {
if (result[state]){
$.each(result[state], function (i, value) {
city.append($("<option></option>").attr("value", value).text(value));
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="state" name="state">
<option value="State #1"> State #1 </option>
<option value="State #2"> State #2 </option>
</select>
<select id="city" name="city"></select>

关于javascript - jQuery 和 JSON : chained select from an array with multiple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560215/

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