当jQuery UI从1.8更新到1.12时,Catcomplete小部件停止工作

时间:2016-11-01 19:42:17

标签: javascript jquery jquery-ui jquery-widgets

这是我的代码,一直运行良好,直到我更新到jQuery UI 1.12

var currentCategory = "";
$.widget("custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function (ul, items) {
        var self = this;
        $.each(items, function (index, item) {
            if (item.category != currentCategory) {
                ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                currentCategory = item.category;
            }
            self._renderItem(ul, item);
        });
    },
    _renderItem: function (ul, item) {
        var clase = '';
        switch (item.category) {
        case 'Usuarios':
            return $("<li class='" + clase + "'></li>")
                .data("item.autocomplete", item)
                .append("<a><img src='" + item.img + "' /><span class='name'>" + item.value + "</span></a>")
                .appendTo(ul);
            break;
        case 'Posts':
            return $("<li class='" + clase + "'></li>")
                .data("item.autocomplete", item)
                .append("<a><img src='" + item.img + "' /><span class='name'>" + item.value + "</span><span class='sub'><i class='fa fa-bookmark-o'></i> " + item.sub + "</span> <span class='sub'>" + item.votos + "<i class='fa fa-thumbs-o-up'></i></span> </a>")
                .appendTo(ul);
            break;
        }
    }
});

这就是我使用它的方式:

$("#recipeName").catcomplete({
        source: "/jsonR.php",
        minLength: 2,
        selectFirst: true,
        select: function (event, ui) {
            console.log(ui); /* this logs Object item:undefined */
            var url = '';
            if (ui.item.category == 'Posts') {  /* This is line 1692 */
                url = 'http://example.com/page.php?id=' + ui.item.id;
            }
            location.href = url;
            return false;
        },
        selectFirst: true,
        open: function () {
            $('.ui-autocomplete').addClass('searchBox');
            currentCategory = "";
        }
    });

此代码正确呈现列表,问题是当我选择一个选项时:

cached.js:1692 Uncaught TypeError: Cannot read property 'category' of undefined(…)

知道我应该从这段代码中重新适应什么才能使用jquery ui 1.12?

- 编辑 -

我注意到,如果使用self._renderItemData(ul, item)代替self._renderItem(ul, item),则选择有效,

问题是我在悬停元素时遇到错误(光标不是指针......):

jquery-ui.js:5840 Uncaught TypeError: Cannot read property 'value' of undefined(…)

这是jquery ui上的第5840行:

// Announce the value in the liveRegion
label = ui.item.attr( "aria-label" ) || item.value;

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我错过了_create方法,我不确定在旧版本中是否有必要

$.widget("custom.catcomplete", $.ui.autocomplete, {
   _create: function() {
            this._super();
            this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
    }
    // Rest of code..
});