Before you point me to them, yes, I have reviewed the half dozen posts on this topic, but I am still stymied as to why this doesn't work.

我的目标是检测自动完成何时产生0个结果.以下是代码:

 $.ajax({
   url:'sample_list.foo2',
   type: 'get',
   success: function(data, textStatus, XMLHttpRequest) {
      var suggestions=data.split(",");

  $("#entitySearch").autocomplete({ 
    source: suggestions,
    minLength: 3,
    select: function(e, ui) {  
     entityAdd(ui.item.value);
     },
    open: function(e, ui) { 
     console.log($(".ui-autocomplete li").size());
     },
    search: function(e,ui) {
     console.log("search returned: " + $(".ui-autocomplete li").size());

    },
    close: function(e,ui) {  
     console.log("on close" +  $(".ui-autocomplete li").size());    
     $("#entitySearch").val("");
    }
   }); 

  $("#entitySearch").autocomplete("result", function(event, data) {

   if (!data) { alert('nothing found!'); }

  })
 }
}); 

The search itself works fine, I can get results to appear without a problem. As I understand it, I should be able to intercept the results with the autocomplete("result") handler. In this case, it never fires at all. (Even a generic alert or console.log that doesn't reference the number of results never fires). The open event handler shows the correct number of results (when there are results), and the search and close event handlers report a result size that is always one step behind.

I feel like I'm missing something obvious and glaring here but I just don't see it.

推荐答案

jQueryUI 1.9

jQueryUI 1.9 has blessed the autocomplete widget with the response event, which we can leverage to detect if no results were returned:

Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled.

So, with that in mind, the hacking we had to do in jQueryUI 1.8 is replaced with:

$(function() {
    $("input").autocomplete({
        source: /* */,
        response: function(event, ui) {
            // ui.content is the array that's about to be sent to the response callback.
            if (ui.content.length === 0) {
                $("#empty-message").text("No results found");
            } else {
                $("#empty-message").empty();
            }
        }
    });
});​

Example: http://jsfiddle.net/andrewwhitaker/x5q6Q/


jQueryUI 1.8

我找不到使用jQueryUI API执行此操作的直接方法,但是,您可以用自己的函数替换autocomplete._response函数,然后调用默认的jQueryUI函数(updated to extend the autocomplete's 101 object):

var __response = $.ui.autocomplete.prototype._response;
$.ui.autocomplete.prototype._response = function(content) {
    __response.apply(this, [content]);
    this.element.trigger("autocompletesearchcomplete", [content]);
};

And then bind an event handler to the autocompletesearchcomplete event (contents is the result of the search, an array):

$("input").bind("autocompletesearchcomplete", function(event, contents) {
    $("#results").html(contents.length);
});

What's going on here is that you're saving autocomplete's response function to a variable (__response) and then using apply to call it again. I can't imagine any ill-effects from this method since you're calling the default method. Since we're modifying the object's prototype, this will work for all autocomplete widgets.

Here's a working example: http://jsfiddle.net/andrewwhitaker/VEhyV/

我的示例使用本地数组作为数据源,但我认为这不重要.


Update: You could also wrap the new functionality in its own widget, extending the default autocomplete functionality:

$.widget("ui.customautocomplete", $.extend({}, $.ui.autocomplete.prototype, {

  _response: function(contents){
      $.ui.autocomplete.prototype._response.apply(this, arguments);
      $(this.element).trigger("autocompletesearchcomplete", [contents]);
  }
}));

将电话从.autocomplete({...});改为:

$("input").customautocomplete({..});

然后绑定到自定义autocompletesearchcomplete事件:

$("input").bind("autocompletesearchcomplete", function(event, contents) {
    $("#results").html(contents.length);
});

See an example here: http://jsfiddle.net/andrewwhitaker/VBTGJ/


Since this question/answer has gotten some attention, I thought I'd update this answer with yet another way to accomplish this. This method is most useful when you have only one autocomplete widget on the page. This way of doing it can be applied to an autocomplete widget that uses a remote or local source:

var src = [...];

$("#auto").autocomplete({
    source: function (request, response) {
        var results = $.ui.autocomplete.filter(src, request.term);

        if (!results.length) {
            $("#no-results").text("No results found!");
        } else {
            $("#no-results").empty();
        }

        response(results);
    }
});

Inside the if is where you would place your custom logic to execute when no results are detected.

Example: http://jsfiddle.net/qz29K/

If you are using a remote data source, say something like this:

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

然后,您需要更改代码,以便自己进行AJAX调用,并在返回0个结果时进行检测:

$("#auto").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "my_remote_src", 
            data: request,
            success: function (data) {
                response(data);
                if (data.length === 0) {
                    // Do logic for empty result.
                }
            },
            error: function () {
                response([]);
            }
        });
    }
});

Jquery相关问答推荐

在 Laravel 中使用 jQuery post 按相关值过滤 Select 选项,如何显示从控制器返回的数据?

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

通过 jQuery 提取 application/json 数据

jQuery 1.4.1 中缺少 JSON 字符串化?

document.querySelector 一个元素中的多个数据属性

在 jQuery 中,我想删除 div 中的所有 HTML

标识符 (id) 是否有通配符 Select 器?

如何使用 jQuery 以编程方式触发对链接的点击?

使用 jQuery click 处理锚点 onClick()

JQuery 仅在 Rails 4 应用程序中的页面刷新时加载

jQuery中追加的相反

根据弹出框相对于窗口边缘的 X 位置更改 Bootstrap 弹出框的位置?

Select 除第一个之外的所有子元素

停止输入/书写后如何触发输入文本中的事件?

如何通过js打开 Select 文件对话框?

用 Javascript 加载 jQuery 并使用 jQuery

jquery可排序占位符高度问题

更改 div 的内容 - jQuery

jquery $(window).width() 和 $(window).height() 在未调整视口大小时返回不同的值

jQuery:通过 .attr() 添加两个属性;方法