【发布时间】:2021-07-31 22:56:45
【问题描述】:
这是我的课程容器 sn-p。我想通过从后端获取数据来创建所有课程的下拉列表(URL:https://ffcc-app.herokuapp.com/get/courses) 在sn-p中,我手动放了一些虚拟课程
<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 从后端获取数据,这是我的代码 sn-p
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 来获取数据,我将不胜感激。
【问题讨论】:
-
您能否详细说明发生了什么?您看到的是什么而不是“所需的输出”。我的第一个猜测是,当您尝试使用“courses1”数组时,它还没有准备好。您是否收到任何错误消息?
-
不,我没有收到任何错误消息,而是收到所有 1514 课程列表,但是当我输入任何字符时,它没有被过滤,而且我无法替换“已选择" 课程名称的类值。
标签: javascript fetch-api