javascript - 如何在我的 JavaScript 中添加搜索功能?
问题描述
我正在使用 JavaScript 开发一个音乐播放器,我正在尝试向我的页面添加一个搜索栏,但是到目前为止我看到的每个教程都使用在 HTML 页面中创建的列表,而我使用 JavaScript 代码创建了一个列表,如下所示:
const songs = [
"BlindingLights.mp3",
"Boyfriend.mp3",
"DontStartNow.mp3",
"Intentions.mp3",
"Physical"
]
const createSongList = () => {
const list = document.createElement('ol')
for(let i = 0; i<songs.length; i++){
const item = document.createElement('li')
item.appendChild(document.createTextNode(songs[i]))
list.appendChild(item)
}
return list
}
document.getElementById('songList').appendChild(createSongList())
有没有办法可以使用“歌曲”数组或开发搜索功能?任何意见,将不胜感激。谢谢!:)
为清楚起见进行编辑:
所以我在我的 html 上有一个输入标签,我想将它用于搜索栏,然后我希望用户输入的内容从歌曲数组中返回任何匹配的歌曲。例如,如果他们输入“Bli”,我希望它显示 Blinding Lights 歌曲。上面的代码片段是我当前使用数组显示歌曲列表的方式。
这是我的输入标签:
<input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">
解决方案
假设你想songs
从搜索字符串中过滤数组,你可以使用这个函数:
const songs = [
"BlindingLights.mp3",
"Boyfriend.mp3",
"DontStartNow.mp3",
"Intentions.mp3",
"Physical"
];
const searchSong = (value) => {
return songs.filter(song => song.includes(value));
};
console.log(searchSong('B'));
推荐阅读
- java - 如何计算 Cloud Firestore 中查询过滤的文档数
- masking - 尝试创建 maskig 策略时出错:“不支持的功能 'MASKING POLICY”
- javascript - 将 Javascript 日期对象转换为其他时区日期对象
- botframework - 在网络聊天机器人框架中动态选择/按下按钮时如何更改按钮背景颜色
- php - 搜索框不返回数据(PHP)
- javascript - 函数调用的 EsLint 逗号样式
- node.js - 在 NODEJS 中获取 PROMISE OBJECT 值
- php - 代码点火器 Jquery。如何使用电子商务循环将数据显示到卡片中
- macos - 在 Mac OS 上寻找系统范围的自动替换
- javascript - 根据属性值对数组进行排序