如何将API返回的站点数据填充到<select>下拉框并生成对应option选项
代码问题排查及修复方案
存在的问题:
- 未初始化
html变量:代码中直接使用html +=拼接字符串,但之前没有声明和初始化html变量,会触发引用错误,导致渲染逻辑终止 - 循环内使用未定义变量:遍历
allstations数组时,没有声明对应的取值变量key、obj,也没有从数组元素中读取站点属性,无法正确拼接option内容 - 可选优化:HTML结构缺少
div、section的闭合标签,虽然部分浏览器会自动补全,但不符合代码规范,建议补全
修正后代码
HTML代码:
<section class="container"> <div class="item"> <p>list</p> <select id="subwaystation"> </select> </div> </section>
JS代码:
var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8"; function req1() { fetch(apiStations, { method: "get" }) .then(response => response.json()) .then(data => { let allstations = data.result.stations; // 初始化存储option的字符串变量 let html = ''; for(var i = 0; i < allstations.length; i++) { // 读取当前遍历的站点信息,slug作为提交值,name作为显示文本 const station = allstations[i]; html += `<option value="${station.slug}">${station.name}</option>` } document.getElementById("subwaystation").innerHTML = html; }) // 新增异常捕获,方便后续排查请求类问题 .catch(err => console.error('站点请求失败:', err)) } req1();
内容的提问来源于stack exchange,提问作者HumDadada
相关产品推荐
相关产品推荐

