如何向我的JavaScript添加搜索功能?

问题描述 投票:1回答:2

我正在使用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上有一个输入标签,我想将其用于搜索栏,然后我希望用户输入什么内容,以便从songs数组中返回所有匹配的歌曲。例如,如果他们输入“ Bli”,我希望它显示“ Blinding Lights”歌曲。上面的代码段是我当前如何使用数组显示歌曲列表的方式。

这是我的输入标签:

<input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">
javascript html
2个回答
1
投票

假设您要从搜索字符串中过滤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'));

0
投票

也许您可以为Array.prototype创建一个新函数search以使其更容易使用

Array.prototype.search = function (keyword) {
  return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}  
const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp6",
    "DontStartNow.mp5",
    "Intentions.mp3",
    "Physical"
];

songs.search('phy ')  // => ["Physical"]
songs.search(' MP3')  // =>  ["BlindingLights.mp3", "Intentions.mp3"]
© www.soinside.com 2019 - 2024. All rights reserved.