我有一个列表要与输入值进行比较,当输入值与列表中的任何内容不匹配时,我想发出提醒(相册不存在)。
这是我的搜索栏: -
<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="sendToPage()">Search</button>`
这是我的清单: -
var validSearch = ["The Stage", "Hail to the King", "Nightmare", "Avenged Sevenfold", "City of Evil", "Waking the Fallen", "Sounding the Seventh Trumpet"];
我已阅读a suggestion,但无法理解它...... :)
答案 0 :(得分:1)
//Your array of valid searches to compare against
var validSearch = ["The Stage", "Hail to the King", "Nightmare", "Avenged Sevenfold", "City of Evil", "Waking the Fallen", "Sounding the Seventh Trumpet"];
//The click handler function
var sendToPage = function(e){
//Get the input value by finding the element by its ID
var album = document.getElementById('search').value;
//Check if the value is in the array
if(validSearch.indexOf(album) < 0){
alert("Album don't exist");
}else{
alert("Album exists");
}
}
&#13;
<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="sendToPage()">Search</button>`
&#13;
答案 1 :(得分:1)
您可以在数组上使用indexOf。它返回匹配元素的索引。 我唯一建议的是你首先将搜索数组调低或大写,所以匹配并不依赖于输入它的人,因为你用每个大写字母完全按照你所写的那样定义了它。 / p>
function match(elem) {
var validSearch = [
"The Stage",
"Hail to the King",
"Nightmare",
"Avenged Sevenfold",
"City of Evil",
"Waking the Fallen",
"Sounding the Seventh Trumpet"];
/** make search case insentive **/
var searchKeys = [];
for(var c=0;c<validSearch.length;c++) {
searchKeys[c] = validSearch[c].toLowerCase();
}
/** search the input **/
var index = searchKeys.indexOf(elem.value.toLowerCase());
/** if not matched **/
if(index == -1) {
window.alert("Album does not exist. Please try again");
}
else {
var album = validSearch[index];
window.alert("FOUND IT! " + album);
}
}
&#13;
<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="match(document.getElementById('search'))">Search</button>
&#13;
答案 2 :(得分:1)
您可以尝试使用正则表达式:可以搜索case insensitive
个关键字,并且可以找到带有限关键字的最近的项目(如果用户不知道如何正确拼写);
var validSearch = ["The Stage", "Hail to the King", "Nightmare", "Avenged Sevenfold", "City of Evil", "Waking the Fallen", "Sounding the Seventh Trumpet"];
function sendToPage() {
//get value and trim for unnecesary spaces, and set variable
var q = document.getElementById("search").value.trim(),
re, result;
//return if textbox is empty
if (!q.length > 0) {
return;
}
//set RegExp (indexOf is faster but Case Sensitive)
re = new RegExp(".*" + q.replace(/\s/g, "\\s") + ".*", "ig");
//start searching
validSearch.some(function(v) {
result = re.exec(v);
if (result) {
return true;
}
})
//if match
if (result !== null) {
alert("Found it!! - " + result[0]);
} else {
alert("Book not Found!! - " + q);
}
//refresh input box
document.getElementById("search").value = "";
}
<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="sendToPage()">Search</button>