【发布时间】:2016-04-22 20:47:41
【问题描述】:
我正在尝试在新网站上显示我的乐队演奏的歌曲列表。用户输入歌曲名称(在名为“liveSearchBox”的输入标签中)并单击“findSong”按钮。如果我们播放这首歌,我想提醒“是的,我们播放它!”。如果我们不这样做,我想提醒“对不起,我们不玩它。”我已经尝试了几个小时来找出解决方案,但还不够先进。谢谢你的帮助!
这是我的 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++;
}
}
};
【问题讨论】:
-
您对哪一部分有问题?为了提醒“否”,您需要一个布尔值,该值最初为假,并且只有在匹配时才设置为真,然后当您的循环完成时,如果布尔值仍然为假,您就知道没有匹配 - 此时您可以提醒“否”。
-
你跳过了很多。不要将
i++放在您的else子句中。您已经在for循环中增加了i。另外,请听 Shomz。有一种更简单的方法。 -
此外,您需要在找到歌曲后添加一个
break;以提前退出for循环。
标签: javascript