我有一个简单的数组,我想循环搜索并搜索用户输入文本框的内容。这就是我所拥有的。请记住,我对JavaScript很陌生:
function recipeInfo(name, ingredients, url) {
this.name = name;
this.ingredients = ingredients;
this.url = url;
}
var vIngredients = new Array();
vIngredients[0] = new recipeInfo("Ackee Pasta", "ackee", "ackpast.html");
vIngredients[1] = new recipeInfo("Ackee and Saltfish", "ackee saltfish", "acksalt.html");
vIngredients[2] = new recipeInfo("Jerk Chicken", "jerk", "jerkchick.html");
// do the lookup
function getData(form) {
// make a copy of the text box contents
var inputText = form.Input.value
// loop through all entries of vIngredients array
for (var i = 0; i < vIngredients.length; i++) {
var list = $("#search-results");
// compare results
if (inputText == vIngredients[i].ingredients) {
console.log(vIngredients[i].name);
//add to the list the search result plus list item tags
list.append (
$("<li class='arrow'><a href='#' >" + vIngredients[i].name + "</a></li>" )
);
}
else {
// advise user
var list = $("#search-results");
// empty list then tell user nothing is found
list.empty();
list.append (
$("<li>No matches found for '" + inputText + "'</li>")
);
}
}
}
</script>
<form name="search" id="search" action="">
<ul class="rounded">
<li><input type="search" name="Input" placeholder="Search..." onkeydown="if (event.keyCode == 13) getData(this.form)"></li>
</ul>
<ul class="edgetoedge" id="results">
<li class="sep">Results</li>
</ul>
<ul class="edgetoedge" id="search-results">
</ul>
</form>
以下是我遇到的问题:
谢谢!
答案 0 :(得分:0)
对于#1,您希望查看数组槽中的文本是否包含键入的字作为子字符串。这样做:
// compare results
if (vIngredients[i].ingredients.indexOf(inputText) != -1) {
对于#2,list.empty()应该这样做。如果没有找到结果,您可以在“其他”块中找到该内容。
对于#3你怎么知道实际上找到了结果? “inputText == vIngredients [i] .ingredients”是否评估为“true”?是console.log(vIngredients [i] .name);按照你的预期记录?
如果您是javascript的新手,您可能不了解各种浏览器开发人员工具中的断点调试程序。这些都是非常宝贵的。