【问题标题】:How to patch just one instance of autocomplete on a page continued如何在页面上仅修补一个自动完成实例(续)
【发布时间】:2012-01-09 18:52:42
【问题描述】:

记住这篇文章 (How to patch *just one* instance of Autocomplete on a page?)

我正在尝试做类似的事情,除了我想有条件地覆盖 _renderMenu 函数。基本上,我希望能够拥有一个 maxResults 属性,如果列表中的项目数超过该值,我想将列表截断为 maxResults 并将“超出最大结果”消息/项目附加为最后一项列表。

例如:

var self = this;
$.each( items, function(index, item) {
    var max = maxResults;  // here we define how many results to show

    if (index < max) {
      self._renderItem(ul, item);
    }
    else if (index == max) {
      var message = "<span class='auto-complete-max-results'>" + 
        items.length + " results - Add more characters to refine results" +
        "</span>";

      return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append( message )
          .appendTo( ul );
    }
  });

我遇到的主要问题之一是如何有条件地覆盖该方法和/或如果我总是覆盖它,我可以调用超级实现吗?

【问题讨论】:

    标签: jquery jquery-ui jquery-autocomplete


    【解决方案1】:

    这就是我解决这个问题的方法。在自动完成字段初始化期间,我执行以下操作:

    $(fieldId).autocomplete({
        ...
      }).data('maxResults', maxResults);
    

    然后我这样做:

    var defaultRenderMenu = $.ui.autocomplete.prototype._renderMenu;
    
    $.ui.autocomplete.prototype._renderMenu = function(ul, items) {
    
      var autoField = this.element;  
      var max = autoField.data('maxResults');
      var numResults = items.length;
    
      // if maxResults is defined and the number of results exceeds the max, we want to trim the list
      if (max != null && numResults > max) {
        var self = this;
    
        $.each( items, function(index, item) {
          // render all items less than the max normally
          if (index < max) {
            self._renderItem(ul, item);
          }
          else if (index == max) {
            var message = "<span class='auto-complete-max-results'>" + 
              "*** " + items.length + " results - Add more characters to refine results ***" +
              "</span>";
    
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append(message)
                .appendTo(ul);
          }
          else {
            return false;  // break out of loop after max
          }
        });
      }
      // otherwise, use the default implementation of renderMenu
      else {
        defaultRenderMenu.apply(this, [ul, items]);
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2013-02-05
      • 2012-03-29
      • 2012-10-28
      • 2011-10-07
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多