javascript Jquery UI 自动完成自定义 HTML(项目未定义)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4908216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:19:47  来源:igfitidea点击:

Jquery UI Autocomplete Custom HTML (item is undefined)

javascriptjqueryjquery-uiautocompletejquery-ui-autocomplete

提问by Nick

I've been banging my head off my desk trying to get the jQuery UI Autocomplete to output custom HTML. Here is my code.

我一直在努力让 jQuery UI 自动完成功能输出自定义 HTML。这是我的代码。

        $(document).ready(function(){

        $.widget( "custom.catcomplete", $.ui.autocomplete, {
            _renderMenu: function( ul, items ) {
                var self = this,
                    currentCategory = "";
                $.each( items, function( index, item ) {
                    if ( item.category != currentCategory ) {
                        ul.append( "<li class='ui-autocomplete-category'>" + item.category + "<ul class='autocomplete-category'></ul></li>" );
                        currentCategory = item.category;
                    }
                    self._renderItem( ul, item);
                });
            }
        });

        var data = [
            { label: "anders", category: "Antigen" },
            { label: "andreas", category: "Antigen" },
            { label: "antal", category: "Antigen" },
            { label: "annhhx10", category: "Products" },
            { label: "annk K12", category: "Products" },
            { label: "annttop C13", category: "Products" },
            { label: "anders andersson", category: "People" },
            { label: "andreas andersson", category: "People" },
            { label: "andreas johnson", category: "People" }
        ];

        $( "#typeAhead" ).catcomplete({
            delay: 0,
            source: data,
        })
        .data( "catcomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.catcomplete", item )
                .append( $( "<a class='ui-menu-item'></a>" ).text( item.label ) )
                .appendTo( $('ul').last('.autocomplete-category'));
        };
    });

I seem to be running into trouble by nesting my lists in the renderItem function. The HTML output is exactly how I want it. However when I "keydown" the I get a javascript error (item is undefined).

通过将列表嵌套在 renderItem 函数中,我似乎遇到了麻烦。HTML 输出正是我想要的。但是,当我“按下键”时,我收到一个 javascript 错误(项目未定义)。

Any ideas or suggestions? I've tried just about everything.

有什么想法或建议吗?我已经尝试了几乎所有的东西。

回答by Andrew Whitaker

You were almost there! I only made two changes to get this to work (Updated after comments from OP):

你快到了!我只做了两个更改才能使其正常工作(在 OP 发表评论后更新):

After digging into the jQueryUI autocomplete source, it looks like the underlying menu that's used by the autocomplete widget isn't too friendly toward nested elements.

在深入研究 jQueryUI 自动完成源后,看起来自动完成小部件使用的底层菜单对嵌套元素不太友好。

I could be wrong about this, but I think the menu expects a simple <ul>with just children <li>s containing an anchor tag.

我可能是错的,但我认为菜单需要一个简单的<ul>,只有 children <li>s 包含一个锚标签。

Edit: This line confirms my suspicion about the menu (found in jqueryUI 1.8.9's menu widget):

编辑:这一行证实了我对菜单的怀疑(在 jqueryUI 1.8.9 的菜单小部件中找到):

    var items = this.element.children("li:not(.ui-menu-item):has(a)")
        .addClass("ui-menu-item")
        .attr("role", "menuitem");

    items.children("a")
        .addClass("ui-corner-all")
        .attr("tabindex", -1)
        // mouseenter doesn't work with event delegation
        .mouseenter(function( event ) {
            self.activate( event, $(this).parent() );
        })
        .mouseleave(function() {
            self.deactivate();
        });

Basically, since your atags were buried inside a nested list, they weren't getting recognized by the menu.

基本上,由于您的a标签隐藏在嵌套列表中,因此菜单无法识别它们。

I bet you noticed in your original code that your autocomplete menu items were not highlighting when you moused over them. This highlighting actually coincides with which menu item the widget thinks is active, which was causing your widget to fail when the user selected an item.

我敢打赌,您在原始代码中注意到,当您将鼠标悬停在自动完成菜单项上时,它们没有突出显示。这种突出显示实际上与小部件认为处于活动状态的菜单项一致,这会导致您的小部件在用户选择项目时失败。

Since there's nothing semantically wrong or visually wrong with just giving the category lis a different class, I would restructure the widget's menu like this:

由于仅仅为类别提供li不同的类在语义上或视觉上没有任何错误,我会像这样重构小部件的菜单:

JavaScript:

JavaScript:

_renderItemfunction:

_renderItem功能:

.data( "catcomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( $( "<a class='ui-menu-item'></a>" )
                 .text( item.label ) )
        .appendTo(ul);
};

Your _renderMenufunction:

你的_renderMenu功能:

_renderMenu: function( ul, items ) {
    var self = this,
        currentCategory = "";
    $.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);
    });
}

Generated HTML for AutoComplete menu:

为自动完成菜单生成的 HTML:

<ul class="ui-autocomplete>
    <li class="ui-autocomplete-category">Antigen</li>
    <li class="ui-menu-item" role="menuitem">
         <a class="ui-menu-item ui-corner-all" tabindex="-1">anders</a>
    </li>
    <li class="ui-menu-item" role="menuitem">
        <a class="ui-menu-item ui-corner-all" tabindex="-1">andreas</a>
    </li>
    <li class="ui-menu-item" role="menuitem">
        <a class="ui-menu-item ui-corner-all" tabindex="-1">antal</a>
    </li>
    <!-- More categories, items, etc.-->
</ul>

Judging by your comments, it seemed like you wanted the menu's HTML to be nested uls inside of lis for each category. Let me know if changing the HTML of the generated menu isn't an option for you for some reason.

从您的评论来看,您似乎希望菜单的 HTML 嵌套在uls 内,li用于每个类别。如果出于某种原因更改生成菜单的 HTML 不适合您,请告诉我。

I've updated the example: http://jsfiddle.net/andrewwhitaker/pjs7a/2/

我已经更新了这个例子:http: //jsfiddle.net/andrewwhitaker/pjs7a/2/

Hope that helps.

希望有帮助。