我正在尝试在我的网络应用程序中添加一个搜索框,以使用户能够搜索所需的电影。我正在从控制台中的 API 获取所有相关数据。唯一的问题是,我不想在每次搜索后在下拉列表中添加新项目,而是只想显示该特定输入的相关电影项目。
请帮忙 :)
这是javascript代码
//API KEY
const API_KEY= 'ecdb4cd2';
const selectBox = document.getElementById("select-box");
const searchInput = document.querySelector("#searchInput");
const select = document.getElementById("select");
function getData(url){
fetch(url)
.then((response)=> response.json())
.then((data)=>{
console.log('Data:', data.Search);
let MoviesList = data.Search;
for(var i = 0; i < MoviesList.length; i++){
var option = document.createElement("OPTION"),
txt = document.createTextNode(MoviesList[i].Title);
option.appendChild(txt);
option.setAttribute("value",MoviesList[i].Title);
select.insertBefore(option,select.lastChild);
}
})
.catch(err=> console.log(err))
}
//fetch data from the api
selectBox.onclick =function(e){
e.preventDefault();
const value=searchInput.value;
const url="http://www.omdbapi.com/?apikey=e94d2f36&s="
//generate the url based on the user input
const newUrl= url + value
console.log(newUrl)
getData(newUrl);
}