루프를 통해 사용자가 텍스트 상자에 입력 한 내용을 검색하려는 간단한 배열이 있습니다. 여기에 내가 가진 것이있다. 마음에 베어 나는 자바 스크립트에 아주 새로운 오전 : 여기 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 개 이상 있으므로 배열에있는 단어 대신 해당 단어를 검색 할 수 있기를 원합니다.
- 누군가 검색을하면 목록은 계속 유지됩니다. 기존 목록에 추가. 검색 전의 내용을 어떻게 지울 수 있습니까?
- 마지막으로 결과가 있는지 여부에 관계없이 결과 대신 항상 일치하는 항목이 표시되지 않으면 사용자에 대한 내 의견이 표시됩니다. 해당 섹션을 주석 처리하면 검색 작업이 정상적으로 수행되지만 일치 항목이없는 경우 의견없이 알 수 있습니다.
고마워요!
# 1의 해결책은 효과가 있습니다. 고맙습니다! 그러나 # 2의 경우, list.empty(); 전에 list.append(); 마지막 엔트리 하나만 보여준다. 그래서 나의 예제에서 ackee를 검색하면 콘솔에 두 항목이 모두 표시되지만 html 출력은 Ackee와 Saltfish 만 있습니다. 마지막으로 # 3. 콘솔은 항상 내가 원하는 것을 보여 주지만 html로 작성하는 경우 작동하지 않습니다. – n00bz0rd2
저는 2 번을 분류 해 냈습니다. 나는 목록 선언과 my list.empty()를 옮겼다. 내 기능 (내 루프 이전) 아래에. 그러나 여전히 내 else 문을 사용할 수 없습니다. – n00bz0rd2