2012-02-15 45 views
2

我正在使用jQuery自动完成搜索字段。当自动完成源返回0结果的响应时,自动完成感觉会中断。我如何总是在自动完成的底部添加帮助消息。如何追加帮手消息到jQuery结束自动完成

我希望帮手信息出现在焦点上,并且随时有0个或更多结果。以下是我迄今为止:

 var me = this, 
      cache = {}, // Autocomplete Caching (not built into jQuery UI by default) 
      lastXhr, 
      ac_div = $("#header-search-q"); 

     ac_div.autocomplete({ 
      appendTo: "#header-search", 
      source: function(request, response) { 
       var term = request.term.toLowerCase(); 
       if (term in cache) { 
        response(cache[ term ]); 
        return; 
       } 
       lastXhr = $.getJSON("https://stackoverflow.com/users/search", _(request).extend({'q_type':'all'}), function(data, status, xhr) { 
        cache[ term ] = data.users; 
        if (xhr === lastXhr) { 
         response(data.users); 
        } 
       }); 
      } 
     }) 
     .data("autocomplete")._renderItem = function(ul, item) {   
      return $('<li></li>') 
      .data("item.autocomplete", item) 
      .append("<a>" + item.label + "</a>") 
      .appendTo(ul); 
     }; 
    } 

我怎样才能始终有一个LI这样在自动完成:

<li class="helper">Can't find them?</a> 

感谢

回答

1

source你或许可以做一个小的黑客功能,像这样:

source: function(request, response) { 
       var term = request.term.toLowerCase(); 
       if (term in cache) { 
        response(cache[ term ]); 
        return; 
       } 
       lastXhr = $.getJSON("https://stackoverflow.com/users/search", _(request).extend({'q_type':'all'}), function(data, status, xhr) { 
        cache[ term ] = data.users; 
        if (xhr === lastXhr) { 
         /* Hack follows: */ 
         if(!data.users.length) data.users.push("Can't find them?"); 
         response(data.users); 
        } 
       }); 
      } 

我最近摆弄自动完成源代码,我发现它很容易定制和改变它的行为,所以这是另一种选择。