我试图显示我的乐队在新网站上播放的歌曲列表。用户输入歌曲名称(在输入标签中称为" liveSearchBox")并点击" findSong"按钮。如果我们播放这首歌,我想提醒一下#34;是的,我们播放它!"。如果我们不这样做,我想提醒"抱歉,我们不会播放它。"我已经花了好几个小时才弄清楚解决方案,但还不够先进。谢谢你的帮助!
这是我的HTML代码:
<div class="live-search-list">
<input type="text" id="liveSearchBox" placeholder=" Search Songs or Artist">
<button id="findSong"> Click to Find!</button>
<ul id="songList">
<li class="song"> Margaritaville</li>
<li class="song"> Boys of Summer</li>
<li class="song"> Somebody Like You</li>
</ul>
</div>
这是我的Javascript:
var songList = ["Margaritaville","Boys of Summer","Somebody Like You"];
var findButton = document.getElementById("findSong");
var songQuery = document.getElementById("liveSearchBox");
var songListItem = document.getElementsByClassName("song");
findButton.onclick = function(){
for (var i = 0; i<songList.length; i++){
if (songQuery.value === songList[i]){
alert('Yes, we play "' + songQuery.value + '"!');
} else {
i++;
}
}
};
答案 0 :(得分:3)
使用indexOf
:
if (songList.indexOf(songQuery.value) != -1)
alert('yes');
else
alert('no');
答案 1 :(得分:1)
使用indexOf
会有效,但如果你想要一个适用于任何浏览器的解决方案,这是最快的方法:
function isInArray(array, item) {
for (i = 0; i < array.length; i++)
if (array[i] === item)
return true;
return false;
}
findButton.onclick = function() {
if (isInArray(songList, songQuery.value))
alert('Yes, we play "' + songQuery.value + '"!');
else
alert('Sorry, we don\'t play "' + songQuery.value + '".');
};
答案 2 :(得分:0)
findButton.onclick = function(){
var msg = !!~songList.indexOf(songQuery.value) ? 'Yes, we play "' + songQuery.value + '"!' : 'No we do not play this song.';
alert(msg);
}
也许这对你来说更容易理解:
findButton.onclick = function(){
var msg = songList.includes(songQuery.value) ? 'Yes, we play "' + songQuery.value + '"!' : 'No we do not play this song.';
alert(msg);
}
或者这个:
findButton.onclick = function(){
if(songList.includes(songQuery.value)) {
alert('Yes, we play "' + songQuery.value + '"!');
} else {
alert('No we do not play this song.');
}
}
答案 3 :(得分:0)
var songList = ["Margaritaville", "Boys of Summer", "Somebody Like You"],
findButton = document.getElementById("findSong"),
songQuery = document.getElementById("liveSearchBox");
findButton.onclick = function() {
if (typeof songQuery.value === 'undefined' || songQuery.value === null || songQuery.value === '') {
alert('please input the song name.');
return false;
}
if (songList.indexOf(songQuery.value) > -1) {
alert('Yes, we play "' + songQuery.value + '"!');
} else {
alert('Sorry "' + songQuery.value + '" was not found!');
}
};
<div class="live-search-list">
<input type="text" id="liveSearchBox" placeholder=" Search Songs or Artist">
<button id="findSong">Click to Find!</button>
<ul id="songList">
<li class="song">Margaritaville</li>
<li class="song">Boys of Summer</li>
<li class="song">Somebody Like You</li>
</ul>
</div>