首页 > 解决方案 > 如何在我的 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()">

标签: javascripthtml

解决方案


假设你想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'));


推荐阅读