【发布时间】:2011-03-10 17:02:18
【问题描述】:
我有一个简单的数组,我想循环并搜索用户在文本框中输入的任何内容。这就是我所拥有的。请记住,我对 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>
以下是我遇到的问题:
- 我的搜索只寻找完全匹配。在我的示例中,“ingredients”属性将包含超过 1 个单词,因此我希望能够搜索这些单词中的任何一个而不是数组中的确切内容
- 如果有人搜索,列表只会继续附加到现有列表。如何在每次搜索之前删除内容?
- 最后,如果没有找到匹配项,我对用户的反馈总是显示而不是结果,无论是否有结果。注释掉该部分会使搜索正常工作,但如果没有匹配项,则没有反馈。
谢谢!
【问题讨论】:
标签: javascript arrays loops