0

Attempting to filter out content on the page based on a jQuery UI autocomplete search. When the user is typing content not related to the search will switch to display: none; so only the content relevant to the search is displayed.

HTML

        <div class="items" data-id="Get Milk">Get Milk on the way home</div>
        <div class="items" data-id="Drop by Phil's">Drop by Phils house</div>
        <div class="items" data-id="Grab a Sandwich">Grab a sandwich</div>

<input id="auto" type="text" />

Javascript

$(function () {
    var source = $(".items").map(function () {
        return $(this).data("id");
    }).get();

    $("#auto").autocomplete({
        source: source        
    });
});​

Attempting with

$(document).ready(function () {

    var search = $("#auto").html();
    var results = $(".items").html();

    if (search == results) {
        $(".items").css("display", "block");
    } 
    else {
        $(".items").css("display", "none");
    }

});

Now I do understand that I need to refer to the individual "items" and this also needs to be demystified. ​ jsfiddle: http://jsfiddle.net/J5rVP/25/ Courtesy Andrew Whitaker, from bit.ly/U1gjr2

4

1 回答 1

1

好的,首先要了解您正在处理一个 jQueryUI 小部件。它们很棒且可扩展,但您必须深入研究文档以确保您了解它们的工作原理。

当您初始化自动完成时,您将需要提供一个响应功能,您可以在其中检查匹配项并在需要时隐藏。像这样:

$("#auto").autocomplete({
    source: source,
    response: function(event, ui){
        if(ui.content.length == 0)
            alert("nothing");
        else
           alert(ui.content.length + " items");
    }
});

最后,请仔细阅读自动完成文档。你会在那里学到很多关于 jQuery UI API 的知识。

http://api.jqueryui.com/autocomplete/

于 2012-12-21T02:32:11.247 回答