使用JavaScript Fetch API拉取后端数据生成可搜索课程下拉列表求助
问题修复方案
首先先把HTML中.options-container里的静态模拟数据全部清空,后续由接口返回数据动态生成:
<div class="options-container"> <!-- 原有静态option全部删掉,留空即可 --> </div>
替换原有JS代码为以下内容:
const point = 'https://ffcc-app.herokuapp.com/get/courses'; let courses1 = []; const opt = document.querySelector(".options-container"); // 正确选中搜索输入框,不是外层容器 const searchInput = document.querySelector(".search-box input"); const selectedEl = document.querySelector(".selected"); // 渲染课程列表公共方法 function renderCourses(list) { const html = list.map((place, index) => { // 生成唯一id关联radio和label const courseId = `course-${index}`; // 完整课程名称,后续选中要用到 const fullCourseName = `${place.code} , ${place.title} , ${place.credits} , ${place.type}`; return ` <div class="option"> <input type="radio" class="radio" name="category" id="${courseId}" value="${fullCourseName}" /> <label for="${courseId}">${fullCourseName}</label> </div> ` }).join(""); opt.innerHTML = html; } // 拉取接口数据,成功后先渲染全量课程列表 fetch(point) .then(response => response.json()) .then(data => { courses1 = data.courses; // 初始渲染全量课程 renderCourses(courses1); }) function findMatches(wordToMatch, courses1) { return courses1.filter(a => { const regex = new RegExp(wordToMatch, 'gi') return a.code.match(regex) || a.title.match(regex) }); } function displayMatches() { const matchArray = findMatches(this.value, courses1) renderCourses(matchArray); } // 绑定搜索事件 searchInput.addEventListener("change", displayMatches); searchInput.addEventListener("keyup", displayMatches); // 事件委托监听单选框选中事件,动态生成的元素也能触发 opt.addEventListener('change', function(e) { if (e.target.classList.contains('radio')) { // 把选中的课程名称赋值给selected元素 selectedEl.textContent = e.target.value; } })
关键修改说明
- 调整了搜索框的选择器,正确选中输入框元素,保证搜索输入事件可以正常触发
- 把课程列表渲染抽成公共方法,接口请求成功后先渲染全量课程,搜索过滤后也调用同一个方法渲染结果
- 动态生成单选框时设置唯一id,和label的for属性绑定,点击label即可选中对应课程
- 给选项容器绑定change事件委托,适配动态生成的单选框,选中时自动把课程名称赋值给
.selected元素
内容的提问来源于stack exchange,提问作者Sidharth Mishra
相关产品推荐
相关产品推荐

