Jquery: use autocomplete() on input elements added to page after DOM was loaded

放肆的年华 提交于 2019-12-11 11:17:01

问题


I am using this autocomplete Plugin working with Jquery: jQuery Autocomplete Mod

You use it by simple adding $("selector").autocomplete(url [, options]);

There are 5 Input elements (id = channel followed by a number) when the page load that's why I use this code to init the autocomplete plugin on each input:

$(document).ready(function() {
      $('input[id^="channel"]').each(function(){       
        $(this).autocomplete(
          "autocomplete/autocomplete.php",
          {
                some options that don't matter now I guess
          }
        );        
  });
});

But now I also want the autocomplete plugin to work on Input elements (same id syntax) that are added by calling a javascript function (by clicking on a link) after the page is loaded.

I now there is the live() function of Jquery but I just don't know how I should use it here.

I am sure there is a nice and easy way to do it but I just can#t think of the right way at the moment.

Thanks in advance!

Phil


回答1:


Because autocomplete adds the events handlers, there isn't really any good way to get it to work with dynamically added elements. You'd have to modify the plugin so that it would know, perhaps optionally, to apply the handlers dynamically. That's a fair amount of work. An easier way is to abstract the handler into a function, then apply it to the original elements and each new element after it is added, perhaps in a callback.

$(document).ready(function() {
    var nextChannel = $('input[id^="channel"]').length + 1;
    function addAutocomplete( selector) {
        $(selector).each(function(){       
           $(this).autocomplete(
              "autocomplete/autocomplete.php",
              {
                    some options that do not matter now I guess
           });        
        });
    });
    addAutocomplete('input[id^="channel"]');

    $('.addSearch').click( function() {
         var input = $('<input id="channel' + nextChannel + '" type="text" />')
                        .appendTo('form');
         addAutocomplete( input );
         ++nextChannel;
         return false;
    });
});


来源:https://stackoverflow.com/questions/7778471/jquery-use-autocomplete-on-input-elements-added-to-page-after-dom-was-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!