jQuery UI Autocomplete disable Select & Close events

前端 未结 5 1934
离开以前
离开以前 2020-12-06 10:33

I\'m using jQuery UI\'s Autocomplete slightly differently than it was probably created to do.

Basically I want to keep all the same functionality, the only differenc

5条回答
  •  隐瞒了意图╮
    2020-12-06 10:43

    The second syntax using .bind() is simply another way of attaching an event handler to jQueryUI's custom events. This is exactly the same as defining the event handler inside of the widget options (using select: function(event, ui) { })

    Imagine if you had several autocomplete widgets on the page and you wanted to execute the same function when any of them raised the "select" event for example:

    $(".autocomplete").bind("autocompleteselect", function(event, ui) {
        /* Will occur when any element with an autocomplete widget fires the
         * autocomplete select event.
         */
    });
    

    As for cancelling the select event, you have that correct. However, cancelling the close event is a little tougher; it looks like returning false from the event handler won't work (close is fired after the menu is actually closed). You could perform a little hackery and just replace the select function with your own:

    var $input = $("input").autocomplete({
        source: ['Hello', 'Goodbye', 'Foo', 'Bar']
    });
    $input.data("autocomplete").menu.options.selected = function(event, ui) { 
        var item = ui.item.data( "item.autocomplete" );
        $input.focus();
    };
    

    Here's a working example of that: http://jsfiddle.net/ZGmyp/

    I am not sure what the ramifications are of overriding the close event, but it doesn't look like anything crazy is happening in the simple example. I would say that this is kind of an unnatural use of the widget, so there may be unexpected consequences.

提交回复
热议问题