这是我的课程容器片段。我想通过从后端获取数据来创建所有课程的下拉列表(网址:https://ffcc-app.herokuapp.com/get/courses) 在代码片段中,我手动放置了一些虚拟课程
<div class="container">
<form action="#" method="POST">
<h2>Course 1</h2>
<div class="select-box">
<div class="options-container">
<div class="option">
<input type="radio" class="radio" id="film" name="category" value="film" />
<label for="Course 2">Course 1</label>
</div>
<div class="option">
<input type="radio" class="radio" id="dance" name="category" value="dance" />
<label for="Course 2">Course 2</label>
</div>
<div class="option">
<input type="radio" class="radio" id="science" name="category" value="science" />
<label for="Course 3">Course 3</label>
</div>
<div class="option">
<input type="radio" class="radio" id="art" name="category" value="art"/>
<label for="Course 4">Course 4</label>
</div>
<div class="option">
<input type="radio" class="radio" id="music" name="category" value="music"/>
<label for="Course 5">Course 5</label>
</div>
</div>
<div class="selected">
Select Courses
</div>
<div class="search-box">
<input type="text" placeholder="Search..." />
</div>
</div>
</div>
我创建了一个搜索框来过滤课程列表,并在您输入任何字符时显示过滤后的列表。 当您选择任何课程时,它应该用所选课程的名称替换“Selected”类值
我尝试使用 Fetch API 从后端获取数据,这是我的代码片段
const point = 'https://ffcc-app.herokuapp.com/get/courses';
let courses1 =[];
fetch(point)
.then(response => response.json())
.then(data => courses1=data.courses)
function findMatches(wordToMatch,courses1){
return courses1.filter(function place(a){
const regex = new RegExp(wordToMatch,'gi')
return a.code.match(regex) || a.title.match(regex)
});
}
function displayMatches(){
const matchArray = findMatches(this.value,courses1)
const html = matchArray.map(place => {
const regex = new RegExp(this.value,'gi');
const code = place.code.replace(regex,`<span class="hl">${this.value}</span>`);
const title = place.title.replace(regex,`<span class="hl">${this.value}</span>`);
return `
<div class="option">
<input type="radio" class="radio" name="category" />
<label for="course-1"> ${code},${title},${place.credits},${place.type}</label>
</div>
`
}).join("");
opt.innerHTML = html;
}
const search = document.querySelector(".search-box");
const opt = document.querySelector(".options-container");
search.addEventListener("change",displayMatches);
search.addEventListener("keyup",displayMatches);
虽然我能够获取它,但我没有得到我想要的输出,我也想不出用课程值替换“选定”类值的方法。
有人可以帮助我吗?如果您还使用 Fetch API 来获取数据,我将不胜感激。