【问题标题】:jquery Autcomplete how can I always show the renderMenu regardless if there are source matches?jquery Autocomplete 无论是否有源匹配,我如何始终显示 renderMenu?
【发布时间】:2012-06-27 16:55:27
【问题描述】:

我想为我的 jQuery 自动完成功能添加一个助手,如下所示:

    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>")
    }

问题是这个 HELPER 仅在自动完成与 myarray 有至少 1 个搜索匹配时才会显示。如何让菜单在用户集中注意力时始终显示?

谢谢

【问题讨论】:

  • 不是一个真正的答案,但为什么不在每条语句之前附加一个空白值?
  • 因为 _renderMenu 永远不会被调用

标签: jquery jquery-ui autocomplete jquery-ui-autocomplete


【解决方案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/

我个人会采用这种解决方案,因为它侵入性较小。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      相关资源
      最近更新 更多