2012-03-28 35 views
4

我想给助手添加到我的jQuery自动完成如下:jquery自动完成如何始终显示renderMenu,无论是否有源匹配?

var thing = $("#thing").autocomplete({ 
     minLength: 0, 
     source: myarray 
    }) 

    // Override the Render Menu 
    thing.data("autocomplete")._renderMenu= function(ul, items) { 
     var self = this; 
     $.each(items, function(index, item) { 
      self._renderItem(ul, item); 
     }); 
     // Adder 
     ul.append("<a class='helper'>Add <b>\"" + this.term + "\"</b> as a new item</a>") 
    } 

的问题是这个助手只显示了当自动完成了对myArray的至少1个搜索匹配。如何在用户关注时始终显示菜单?

感谢

+0

不是一个真正的答案,但为什么不在每个语句前追加一个空白值? – kpcrash 2012-03-28 01:56:22

+0

因为_renderMenu永远不会被调用 – AnApprentice 2012-03-28 02:05:48

回答

1

我想多一点的猴子修补是为了:

/* Override the _response function to always open the suggestions menu: */ 
thing.data("autocomplete")._response = function(content) {   
    if (!this.options.disabled) { 
     this._trigger("open"); 
     content = this._normalize(content); 
     this._suggest(content); 
    } 

    this.pending--; 
    if (!this.pending) { 
     this.element.removeClass("ui-autocomplete-loading"); 
    } 
}; 

例子:http://jsfiddle.net/eJMuf/

这应该工作,但我会继续寻找一个解决方案使用标准的API。


这里不需要相当多的开放式心脏手术另一种解决方案,但它需要更多的代码:

var thing = $("#thing").autocomplete({ 
    minLength: 0, 
    /* Use a source function instead of the array */ 
    source: function(request, response) { 
     var result = myArray.slice(0); 
     /* Filter the array normally... */ 
     result = $.ui.autocomplete.filter(result, request.term); 

     /* Add a placeholder result that we can process later */ 
     result.push({ 
      value: request.term, 
      isPlaceholder: true 
     }); 
     response(result); 

    } 
}).focus(function() { 
    $(this).autocomplete("search", this.value); 
}); 

var renderItem = thing.data("autocomplete")._renderItem; 
/* Override the _renderItem function to display the placeholder item */ 
thing.data("autocomplete")._renderItem = function(ul, item) { 
    if (item.isPlaceholder) { 
     return $("<li>") 
      .data("item.autocomplete", item) 
      .append("<a class='helper'>Add <b>\"" + item.value + "\"</b> as a new item</a>") 
      .appendTo(ul); 

    } else { 
     renderItem(ul, item); 
    } 
}; 

例子:http://jsfiddle.net/FvCY6/

我会亲自去这个解决方案,因为它侵入性较小。

0

更好的方法是在后端添加一个元素数量的项目。
如果它是一个json数组,然后添加一个带有标签和特殊值为-1的json对象。在这种情况下,该数组将始终包含一个对象。 :)

相关问题