How do you bind jQuery UI autocomplete using .on()?

后端 未结 2 1471
有刺的猬
有刺的猬 2020-12-03 07:52

This question was answered for the live() method, but the live() method has been deprecated as of jQuery 1.7 and replaced with the .on() method and this answer does not work

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 08:14

    This seems just to be some peculiarity of the interaction between .on() and autocomplete. If you want to do this:

    $(function(){
      $('.search').live('keyup.autocomplete', function(){
        $(this).autocomplete({
          source : 'url.php'
        });
      });
    });
    

    This works with on():

    $(function(){
      $(document).on("keydown.autocomplete",".search",function(e){
        $(this).autocomplete({
          source : 'url.php'
        });
      });
    });
    

    You can access the event.target.id of the element that the autocomplete was called on with the parameter of the on() callback function (e in the code above).

    The difference is with on(), the event param in the internal events works differently, holding different values. With live(), the event.target.id in the select function will hold the ID of the selected input element. But with on(), the event.target.id in select will hold the ID of the list of autocomplete items (ui-active-menuitem). With on(), you can access the ID of the input element with event.target.id from the change and open functions.

提交回复
热议问题