jQuery自动完成在字符串中的任何位置搜索匹配项

时间:2013-11-20 19:31:42

标签: javascript jquery

我在jQuery网站上找到自动完成的示例代码时遇到问题> http://api.jqueryui.com/autocomplete/#example-1当我执行以下操作时,我能够在自动完成输入控件中看到我的结果....

这是fetchResponse

var cachedResult = null;
function fetchResponse(callback) {
    if (cachedResult) {
        alert("In cachedResult!");
        callback(cachedResult);
    }
    $.ajax({
        url: "FacilitiesAsync",
        type: 'GET',
        cache: false,
        data: 'sourceDb=myDb',
        dataType: 'json',
        success: function (json) {
            // call autocomplete callback method with results
            alert("Second");
            var cachedResult = $.map(json, function (name) {
                return {
                    label: name.label,
                    value: name.value
                };
            });
            alert("Third");                
            callback(cachedResult);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            $("#autocomplete").text(textStatus + ', ' + errorThrown);
        }
    });
}

$(document).ready(function() {

    $("#autocomplete").autocomplete({
        source: function (request, response) {
            alert("First");
            fetchResponse(function (result) {
                response(result);
            });
        }
    });
});

但是,当我尝试从jQuery网站实现示例中看到的功能时,我根本没有得到任何结果。我希望过滤我的结果,以便用户可以在文本框中键入任何单词,并且列表被过滤,而不仅仅是在开头搜索,但我也不确定RegEx。

更新的代码:我在输入控件中看到了结果,但它们从未被过滤,我在Firefox控制台中收到一个错误,即'elems'未定义。我知道这与我将响应(结果)传递给grep函数有关,但我不知道如何修复它。

$(document).ready(function() {

    $("#autocomplete").autocomplete({
        source: function (request, response) {
            fetchResponse(function (result) {
                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(response(result), function (item) {
                    return response(matcher.test(item.label));
                }));                                        
            });
        }
    });
});

我在fetchedResponse中调用它,因为我需要先获取数据然后才能工作。当我不尝试过滤它时,我在输入控件中看到数据。

请原谅我,我仍然是jQuery的新手。

1 个答案:

答案 0 :(得分:0)

代码需要修改如下,

<强> JS

function fetchResponse(callback) {
    setTimeout(function(){
      /*assuming this is result from ajax*/
      var tags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
      callback(tags);
    },2000);
}

$("#autocomplete").autocomplete({
    source: function (request, response) {
        fetchResponse(function (result) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
            response($.grep(result, function (item) {
                return matcher.test(item);
            }));
        });
    }
});

http://jsfiddle.net/c5YMF/1

相关问题