我要选择与国家和城镇相关的内容
国家数据为
var arr_country=[
{"id": 100,"name":"台北市"},
{"id": 200,"name":"新北市"},
{"id": 300,"name":"桃園市"},
{"id": 400,"name":"新竹縣"},
{"id": 500,"name":"台中市"}
]
var arr_town=[
{"id": 10011,"name":"中正區"},
{"id": 10022,"name":"信義區"},
{"id": 20011,"name":"板橋區"},
{"id": 20022,"name":"永和區"},
{"id": 30011,"name":"龜山區"},
{"id": 30022,"name":"八德區"},
{"id": 40011,"name":"新豐鄉"},
{"id": 40022,"name":"湖口區"},
{"id": 50011,"name":"北屯區"},
{"id": 50022,"name":"大雅區"}
]
HTML代码为
<select id="country"></select>
<select id="town"></select>
我无法更改JSON数据格式
这两个数据的关系是
国家/地区ID = XXX
城市ID = XXXOO
如何过滤匹配数组以动态插入选项以选择城镇
我尝试写一些脚本
var counties_option = '';
for (var i = 0; i < arr_country.length; i++) {
counties_option += '<option value="' + arr_country[i].id + '">' + arr_country[i].name + '</option>';
}
$('#country')
.append(counties_option)
.on('change',function(){
$('#town').empty();
var selected_counties=this.value
var filtered_arr=arr_town.filter(function(item){
return item.id==selected_counties;
});
var town_option = '';
for (var j = 0; j < filtered_arr.length; j++) {
town_option += '<option value="' + filtered_arr[j].id + '">' + filtered_arr[j].name + '</option>';
}
$('#town').append(town_option)}).trigger('change');
这是我的jsFiddle练习=> jsFiddle practice
答案 0 :(得分:2)
像这样更新您的功能
var filtered_arr=arr_town.filter(function(item){
return item.id.toString().substring(0,3)==selected_counties;
});
这正在工作,我也更新了您的jsfiddle。http://jsfiddle.net/nmongiya/0dj6uaph/
答案 1 :(得分:1)
在您尝试发布时,问题似乎出在您生成filtered_arr
的方式上。要获取给定国家/地区的城镇,您可能需要尝试以下操作:
function getTowns(country) {
return arr_town.filter(function(town) {
return Math.floor(town.id / 100) === country.id;
});
}
var arr_country=[
{"id": 100,"name":"台北市"},
{"id": 200,"name":"新北市"},
{"id": 300,"name":"桃園市"},
{"id": 400,"name":"新竹縣"},
{"id": 500,"name":"台中市"}
];
var arr_town=[
{"id": 10011,"name":"中正區"},
{"id": 10022,"name":"信義區"},
{"id": 20011,"name":"板橋區"},
{"id": 20022,"name":"永和區"},
{"id": 30011,"name":"龜山區"},
{"id": 30022,"name":"八德區"},
{"id": 40011,"name":"新豐鄉"},
{"id": 40022,"name":"湖口區"},
{"id": 50011,"name":"北屯區"},
{"id": 50022,"name":"大雅區"}
];
console.log(getTowns(arr_country[0]));
console.log(getTowns(arr_country[1]));
console.log(getTowns(arr_country[2]));