我在使用我在 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 网站示例中的功能时,我根本没有得到任何结果。我希望过滤我的结果,以便用户可以在文本框中键入任何单词,并且列表被过滤,而不仅仅是在开始时搜索,但我也不确定正则表达式。
更新的代码:我在输入控件中看到结果,但它们从未被过滤,并且我在 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 的新手。
最佳答案
代码需要修改如下,
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);
}));
});
}
});
关于javascript - jQuery 自动完成在字符串中的任何位置搜索匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20105202/