JS实现选中下拉框国家后从数组取数生成对应信息段落
核心问题说明
你现有代码无法正常运行的原因有两点:
new Option()构造函数参数传参错误,该API的标准入参顺序为「选项显示文本、选项值、默认选中状态、当前选中状态」,你误将国土面积字段作为第三个参数传入,没有正确关联选项和对应国家的完整数据。- 没有绑定下拉框的
change事件监听,仅在页面初始化阶段读取了一次下拉框值,用户切换选项时不会触发段落内容更新。
完整实现代码
首先准备对应的DOM结构:
<select id="countries"></select> <p id="countryDesc"></p>
对应JS逻辑如下:
const countries = [ {name: 'Belgium', population: 11.46, km: 30689}, {name: 'France', population: 67.06, km: 643801}, {name: 'USA', population: 238.2, km: 9834000}, {name: 'Russia', population: 144.4, km: 17130000}, {name: 'China', population: 1398, km: 9597000}, ]; const selectDom = document.getElementById('countries'); const descDom = document.getElementById('countryDesc'); // 生成下拉选项 countries.forEach(country => { selectDom.add(new Option(country.name, country.name)) }); // 定义信息更新方法 function refreshDesc() { const selectedName = selectDom.value; // 从原始国家数组匹配选中项的完整数据 const targetCountry = countries.find(item => item.name === selectedName); // 拼接要求的文本并写入段落 descDom.textContent = `${targetCountry.name} has a population of ${targetCountry.population} million people and is ${targetCountry.km} large.` } // 页面初始化时默认加载第一个国家的信息 refreshDesc(); // 监听下拉选择变化,自动更新段落内容 selectDom.addEventListener('change', refreshDesc);
实现效果
选中比利时选项时,段落将准确展示:
Belgium has a population of 11.46 million people and is 30689 large.
切换其他下拉选项时,会自动匹配对应国家的人口、面积数据更新段落内容,不需要额外操作。
内容的提问来源于stack exchange,提问作者Sheldon Truyens
相关产品推荐
相关产品推荐

