jQuery 自动完成 ._renderItem 并将类添加到包装器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9337796/
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-08-27 10:40:21  来源:igfitidea点击:

autocomplete ._renderItem and adding a Class to wrapper

jqueryjquery-uijquery-autocompletejquery-ui-autocomplete

提问by Control Freak

Going off the example here http://jqueryui.com/demos/autocomplete/#custom-dataI'm wondering how to add a style to the ulwrapper when using _renderItem():

离开这里的例子http://jqueryui.com/demos/autocomplete/#custom-data我想知道如何ul在使用时向包装器添加样式_renderItem()

    .data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
    };

回答by Andrew Whitaker

Here would be one simple way to do it, tapping into the openevent:

这是一种简单的方法,利用open事件:

$("#auto").autocomplete({
    source: /* ... */,
    open: function () {
        $(this).data("autocomplete").menu.element.addClass("my_class");
    }
});

jQueryUI >= 1.9

jQueryUI >= 1.9

$("#auto").autocomplete({
    source: /* ... */,
    open: function () {
        $(this).data("uiAutocomplete").menu.element.addClass("my_class");
    }
});

menuis an internal widget that autocomplete uses.

menu是自动完成使用的内部小部件。

Example:http://jsfiddle.net/bx8Ye/

示例:http : //jsfiddle.net/bx8Ye/

回答by sngregory

If you want to add a style to the ul wrapper then you need to overload _renderMenu() and not _renderItem().

如果要向 ul 包装器添加样式,则需要重载 _renderMenu() 而不是 _renderItem()。

Here is an example that sets the width of the UL and adds a footer as the last li in the ul

这是一个设置 UL 宽度并在 ul 中添加页脚作为最后一个 li 的示例

.data( "autocomplete" )._renderMenu = function( ul, data ) {

    var self = this;
    $(ul).css('width', settings.dropDownWidth);

    $.each( data, function( index, item ) {
        self._renderItem( ul, item );
    });

    $(ul).append("<div class='myFooter'>some footer text</div>");
}; 

回答by ryduh

When using jQuery UI 1.10, I used Andrew Whitaker's answer, but I had to change

使用 jQuery UI 1.10 时,我使用了 Andrew Whitaker 的回答,但我不得不改变

$(this).data("autocomplete").menu.element.addClass("my_class");

to

$(this).data("uiAutocomplete").menu.element.addClass("my_class");