我有一个 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>
也就是说,这些值作为一个值返回,它应该是多个值(每个值用逗号分隔)。