Angular4中根据国家名称联动填充城市下拉框问题求助
嘿,我来帮你搞定这个国家-城市联动下拉框的问题!其实不用折腾复杂的HTTP请求来回绕,直接用HTML+JavaScript就能轻松实现,步骤超简单,我给你捋清楚:
简单实现国家-城市联动下拉框的方案
1. 先搭好HTML基础结构
先准备两个下拉选择框,一个用来选国家,一个用来展示对应城市:
<select id="countrySelect"> <option value="">请选择国家</option> </select> <select id="citySelect"> <option value="">请先选择国家</option> </select>
2. 加载数据并初始化国家下拉框
如果你的JSON数据量不大,直接把数据嵌入到JS里是最省心的方式(不用额外发请求),当然也支持加载外部JSON文件,我两种都给你写:
方式一:直接嵌入JSON数据
// 把你的JSON数据直接放在这里(注意补全缺失的语法,比如你原来的`beautiful: fa...`应该是`false`) const countryData = [ { "countryName": "India", "cities": [ { "id": 1, "name": "Banglaore", "founded": -200, "beautiful": true, "data": 123, "keywords": ["Kaveri", "River"] }, { "id": 2, "name": "Pune", "founded": 0, "beautiful": false } // 补全你剩下的城市数据 ] }, // 可以继续添加其他国家数据 { "countryName": "China", "cities": [ { "id": 3, "name": "Beijing" }, { "id": 4, "name": "Shanghai" } ] } ]; // 初始化国家下拉选项 const countrySelect = document.getElementById('countrySelect'); countryData.forEach(country => { const option = document.createElement('option'); option.value = country.countryName; option.textContent = country.countryName; countrySelect.appendChild(option); });
方式二:加载外部JSON文件(file.json)
如果一定要用外部文件,用fetch就能轻松加载,记得把初始化逻辑封装成函数:
// 加载外部JSON文件 fetch('file.json') .then(response => response.json()) .then(data => { initCountrySelect(data); setupCity联动(data); }) .catch(error => console.error('加载数据失败:', error)); // 初始化国家下拉的函数 function initCountrySelect(data) { const countrySelect = document.getElementById('countrySelect'); data.forEach(country => { const option = document.createElement('option'); option.value = country.countryName; option.textContent = country.countryName; countrySelect.appendChild(option); }); }
3. 监听国家选择,动态填充城市
给国家下拉框加个选择事件监听器,用户选完国家后,自动匹配对应的城市列表并填充到第二个下拉框:
const citySelect = document.getElementById('citySelect'); // 这里如果是用外部JSON的方式,把这个逻辑放到上面的`setupCity联动`函数里 countrySelect.addEventListener('change', function() { // 先清空城市下拉的现有选项 citySelect.innerHTML = '<option value="">请选择城市</option>'; // 获取当前选中的国家名称 const selectedCountry = this.value; if (!selectedCountry) return; // 没选国家就直接返回 // 找到对应国家的城市数据 const targetCountry = countryData.find(item => item.countryName === selectedCountry); if (targetCountry && targetCountry.cities) { // 遍历城市列表,添加到下拉框 targetCountry.cities.forEach(city => { const option = document.createElement('option'); option.value = city.id; // 可以用城市ID当value,也可以直接用城市名称 option.textContent = city.name; citySelect.appendChild(option); }); } });
几个要注意的小细节
- 确保你的JSON数据格式完全正确,比如引号、逗号、布尔值(
true/false不要加引号)都不能错,不然会加载失败; - 如果用外部JSON文件,本地打开HTML时有些浏览器会限制读取本地文件,建议用VSCode的Live Server插件启动本地服务器来运行页面。
这样操作下来,当你选择印度时,城市下拉框就会自动显示Banglaore、Pune这些选项啦,是不是很简单~
内容的提问来源于stack exchange,提问作者manju t
相关产品推荐
相关产品推荐

