旧版本的jQueryUI自动完成控件中的类别

Categories in old version of jQueryUI AutoComplete control

本文关键字:控件 版本 jQueryUI      更新时间:2023-09-26

我被困在jQuery 1.7和jQueryUI 1.8.6上,目前无法升级(我们有相当多的弃用和删除的代码,目前无法升级)。

我可以使用jQueryUI的自动完成控件,但我无法弄清楚如何使用类别-使用这里找到的示例。

$.widget( "custom.catcomplete", $.ui.autocomplete, {
    _create: function() {
      this._super();
      this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
    },
    _renderMenu: function( ul, items ) {
      var that = this,
        currentCategory = "";
      $.each( items, function( index, item ) {
        var li;
        if ( item.category != currentCategory ) {
          ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
          currentCategory = item.category;
        }
        li = that._renderItemData( ul, item );
        if ( item.category ) {
          li.attr( "aria-label", item.category + " : " + item.label );
        }
      });
    }
  });

我得到一个错误:this._super is not a function,如果我删除那行,那么下面的行在调用widget()时失败,使用Cannot read property 'element' of undefined

我知道jQuery插件的语法在不同版本之间发生了变化,但我似乎无法修改他们的示例,以便它可以与旧版本一起工作。这个问题暗示了1.7版本中略有不同的语法,但我只是在摆弄它时不断得到不同的错误。

你知道我需要改变什么才能使它工作吗?

_super方法是在较新版本的jQuery UI中创建的,以前的版本中不存在。作为一种变通方法,你可以调用$.ui.autocomplete.prototype._create.call(this);,它的作用基本上与_super相同。


一旦_renderItemData也没有退出,您必须实现它,通过将其更改为_renderItem,然后调用.data( "ui-autocomplete-item", item );

修改后的完整代码如下:
$.widget("custom.catcomplete", $.ui.autocomplete, {
  _create: function () {
    $.ui.autocomplete.prototype._create.call(this);
    this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
  },
  _renderMenu: function (ul, items) {
    var that = this,
      currentCategory = "";
    $.each(items, function (index, item) {
      var li;
      if (item.category != currentCategory) {
        ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
        currentCategory = item.category;
      }
      li = that._renderItem(ul, item).data('ui-autocomplete-item', item);
      if (item.category) {
        li.attr("aria-label", item.category + " : " + item.label);
      }
    });
  }
});

小提琴工作:http://jsfiddle.net/qjw165sz/1/