通过数组循环并使用JavaScript显示结果?
我有一个简单的数组,我想循环搜索用户在文本框中键入的任何内容。这是我得到的。请记住,我对JavaScript非常陌生:通过数组循环并使用JavaScript显示结果?,javascript,arrays,loops,Javascript,Arrays,Loops,我有一个简单的数组,我想循环搜索用户在文本框中键入的任何内容。这是我得到的。请记住,我对JavaScript非常陌生: function recipeInfo(name, ingredients, url) { this.name = name; this.ingredients = ingredients; this.url = url; } var vIngredients = new Array(); vIngredients[0] = new recipeInfo("Ack
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>
函数recipeInfo(名称、成分、url){
this.name=名称;
这个。成分=成分;
this.url=url;
}
var vingElements=新数组();
VingElements[0]=新的recipeInfo(“Ackee意大利面”、“Ackee”、“ackpast.html”);
VingElements[1]=新的recipeInfo(“Ackee and Saltfish”、“Ackee Saltfish”、“Ackee Saltfish.html”);
VingElements[2]=新的recipeInfo(“Jerk Chick”、“Jerk”、“Jerk Chick.html”);
//进行查找
函数getData(form){
//复制文本框内容
var inputText=form.Input.value
//循环遍历VingElements数组的所有条目
对于(变量i=0;i”)
);
}
否则{
//建议用户
风险值列表=$(“#搜索结果”);
//空列表,然后告诉用户未找到任何内容
list.empty();
list.append(
$(“未找到“'+inputText+” ”的匹配项)
);
}
}
}
- 结果
以下是我遇到的问题:
// compare results
if (vIngredients[i].ingredients.indexOf(inputText) != -1) {
对于#2,list.empty()应该可以。在没有找到结果的情况下,您的“else”块中有这个选项
对于#3,您如何知道实际正在发现结果?“inputText==vingElements[i].Components”的计算结果是否为“true”?不执行console.log(vingElements[i].name);按您的预期登录
如果您是javascript新手,您可能不知道各种浏览器开发人员工具中的断点调试器。这些都是非常宝贵的。您的#1解决方案有效。非常感谢。但是对于#2,当我放置list.empty()时;在list.append()之前;它只显示一个条目,即最后一个条目。因此,在我的示例中,搜索ackee将在控制台中显示这两个条目,但我的html输出仅为ackee和Saltfish。最后#3。控制台总是显示我想要的内容,但当涉及到写入html时,它就不起作用了。我已经设法整理出了#2。我移动了我的list声明和list.empty();在我的函数下面(在我的循环之前)。然而,我的else语句仍然无法运行。