javascript - javascript下拉列表中的动态选项
问题描述
我正在尝试在我的网络应用程序中添加一个搜索框,以使用户能够搜索所需的电影。我正在从控制台中的 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);
}
解决方案
推荐阅读
- qml - 如何在 TextEdit 中逐行设置文本对齐?
- javascript - laravel _token 可以用来避免两次提交表单吗?
- c - 带有读取系统调用的空字符串输入导致分段错误
- javascript - 需要在 x 轴上只有整数 - d3
- html - 将 div 粘贴到父聊天窗口的底部
- java - 格式化 TimeZoneDesignator
- c# - 如何将标题的高度设置为最大高度?
- php - Laravel:如何比较 2 个集合属性
- cassandra - Cassandra 在读取查询期间以一致性 LOCAL_QUORUM 超时(需要 2 个响应,但只有 1 个副本响应)
- powerquery - 消失的列过滤器值