在 jquery 自动完成中覆盖 _rendermenu 会抛出 js 错误

overriding _rendermenu in jquery autocomplete throws js error

我试图覆盖 jquery 自动完成中的 _rendermenu。该列表正在生成,但每次我将鼠标悬停在结果上时,我都会收到以下 js 错误

未捕获类型错误:无法读取 jquery-ui.js

中未定义的 属性 'value'

使用的代码是

$(function () {
var availableTags = [
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme",
                "AA",
                "BB",
                "CC",
                "DD",
                "EE",
                "FF",
                "GG",
                "HH",
                "II",
                "JJ",
                "KK"
            ];


   var atComplete=$( "#autoCompleteText" ).autocomplete({
        delay:0,
        source:availableTags,
             autoFocus: true,
             minLength: 0,
             appendTo: "#result"          
}).focus(function () {
                $(this).autocomplete("search");
 }).data('ui-autocomplete');
   atComplete._renderMenu = function( ul, items ) {
            var that = this;
            $.each( items, function( index, item ) {
                    that._renderItem( ul, item );
            });
    };

    atComplete._renderItem = function(ul, item) {
        console.log("item in render item:",item);
            return $("<li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
    };
});

如果您查看 API docs for _renderMenu,您会发现出错的原因:

Creation of the individual <li> elements should be delegated to _renderItemData(), which in turn delegates to the _renderItem() extension point.

您正在直接使用 renderItem()。这意味着您实际上并没有将项目数据绑定到 .data('ui-autocomplete-item') 缓存,小部件在绘制菜单时会尝试读取它——但由于它未定义,页面会引发错误。

要修复它,您需要做的就是将对 _renderItem 的调用更改为调用 _renderItemData

atComplete._renderMenu = function( ul, items ) {
        var that = this;
        $.each( items, function( index, item ) {
                that._renderItemData( ul, item );
        });
};