【问题标题】:overriding _rendermenu in jquery autocomplete throws js error在 jquery 自动完成中覆盖 _rendermenu 会引发 js 错误
【发布时间】:2016-01-08 22:56:54
【问题描述】:

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

Uncaught TypeError: Cannot read property 'value' of undefined in jquery-ui.js

使用的代码是

$(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);
    };
});

【问题讨论】:

    标签: jquery-ui jquery-autocomplete


    【解决方案1】:

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

    各个

  • 元素的创建应委托给_renderItemData(),而后者又委托给_renderItem() 扩展点。
  • 您正在直接使用renderItem()。这意味着您实际上并未将项目数据绑定到 .data('ui-autocomplete-item') 缓存,小部件在绘制菜单时会尝试读取该缓存 - 但由于它未定义,因此页面会引发错误。

    要解决此问题,您只需将调用 _renderItem 改为调用 _renderItemData

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多