JavaScript中如何复用月份选择的索引值获取对应JSON数据?
问题说明
需要将从JSON文件获取数据时硬编码的data[0]中的0,替换为用户通过下拉菜单选择月份后得到的索引值,实现选择不同月份后自动更新展示的JSON数据。
原有代码
月份选择逻辑
months.forEach((el, index) => { el.onclick = function () { const indexValue = Number(index); const monthSelected = (monthText.textContent = this.innerHTML); console.log(monthSelected); console.log(indexValue); return indexValue; }; });
数据获取逻辑
// Step2 const jsonData = fetch("data.json") .then(function (resp) { return resp.json(); }) .then(function (data) { const generalData = data[0]; // 后续数据处理逻辑 })
解决方案
核心思路是将数据获取逻辑封装为可复用函数,在用户选择月份时传入对应的索引值,触发数据更新:
修改后的完整代码
// 存储当前选中的月份索引,默认选中第一个 let selectedMonthIndex = 0; // 月份选择事件处理 months.forEach((el, index) => { el.onclick = function () { selectedMonthIndex = Number(index); monthText.textContent = this.innerHTML; console.log("选中月份:", this.innerHTML); console.log("对应索引:", selectedMonthIndex); // 触发数据更新 updateMonthData(selectedMonthIndex); }; }); // 封装数据更新函数 function updateMonthData(index) { fetch("data.json") .then(resp => resp.json()) .then(data => { const generalData = data[index]; // 用选中的索引替换硬编码的0 // 这里添加处理generalData的逻辑,比如渲染页面内容 console.log("当前月份数据:", generalData); }) .catch(error => { console.error("数据加载失败:", error); }); } // 页面初始化时加载默认月份数据 updateMonthData(selectedMonthIndex);
说明
- 将原本的fetch逻辑拆分为独立函数
updateMonthData,通过参数接收月份索引,灵活获取对应数据 - 点击月份选项时,立即调用数据更新函数,实现实时切换
- 增加错误捕获逻辑,避免请求失败导致页面异常
- 页面加载时自动加载默认索引的数据,保证初始状态有内容展示
内容的提问来源于stack exchange,提问作者guaPeo USA
相关产品推荐
相关产品推荐

