Appending an item to a jQuery UI autocomplete

2019-04-06 21:57发布

问题:

Currently, I'm using jQuery UI autocomplete on a textbox that references an ASHX file.

Everything is working propertly, except I want to append an item at the end of the list that reads: "Item not found? Click here to request to add a new item."

I tried the following the lines of code, but all it did was format the item's, I was unable to append.

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'));
    };

Hints? Tips? Mucho gracias! :D

回答1:

You should add your extra entry after the Open event fires. That will give you access to the list, which is what you are after, rather than to each element, which is what the _renderItem is giving you access to.

Here's an example styling the entries that have been populated into the list:

$("#myBox").autocomplete({
        source: "[URL]",
        minLength: 2,
        open: function(event, ui) {
            $("ul.ui-autocomplete.ui-menu .ui-menu-item:odd").css("background-color","#dedede");
        }
    });


回答2:

You don't want to fiddle with _renderItem. That is the fn that renders one item; it is called once for each item in the list of suggestions.

What you want to do is monkeypatch the _renderMenu function. The original definition in jQuery UI 1.8.6 is like this:

_renderMenu: function( ul, items ) {
    var self = this;
    $.each( items, function( index, item ) {
        self._renderItem( ul, item );
    });
},

It's probably basically the same for other versions of jQuery UI.

Patch this to add your extra item, after doing the $.each.