【问题标题】:Looping through array and display results using JavaScript?使用 JavaScript 循环遍历数组并显示结果?
【发布时间】: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>

以下是我遇到的问题:

  1. 我的搜索只寻找完全匹配。在我的示例中,“ingredients”属性将包含超过 1 个单词,因此我希望能够搜索这些单词中的任何一个而不是数组中的确切内容
  2. 如果有人搜索,列表只会继续附加到现有列表。如何在每次搜索之前删除内容?
  3. 最后,如果没有找到匹配项,我对用户的反馈总是显示而不是结果,无论是否有结果。注释掉该部分会使搜索正常工作,但如果没有匹配项,则没有反馈。

谢谢!

【问题讨论】:

    标签: javascript arrays loops


    【解决方案1】:

    对于#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 新手,您可能不了解各种浏览器开发工具中的断点调试器。这些都是无价的。

    【讨论】:

    • 您的#1 解决方案有效。谢谢!但是,对于#2,当我放 list.empty();在 list.append() 之前;它只显示一个条目,最后一个。因此,在我的示例中,搜索 ackee 将在控制台中显示这两个条目,但我的 html 输出只有 Ackee 和 Saltfish。最后,#3。控制台总是显示我想要的,但是在写入 html 时,它不起作用。
    • 我已经设法解决了#2。我移动了我的列表声明和我的 list.empty();在我的功能下方(在我的循环之前)。但是仍然无法让我的 else 语句起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多