本文介绍了jQuery的:使用自动完成()输入中的元素添加到页面的DOM加载后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个自动完成插件使用jQuery:

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

您通过简单的添加$(选择),使用它自动完成(网址[,选项]);

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

有5 input元素(ID =通道后跟一个数字)时,这就是为什么我用这个code页面加载的init在每个输入的自动完成插件:

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

但现在我也想自动完成插件上通过调用javascript函数(通过单击链接),在页面加载后添加输入的元素(相同的id语法)工作。

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.

我现在有Jquery的的现场()函数,但我不知道我应该怎么在这里使用它。

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.

在此先感谢!

菲尔

推荐答案

由于自动完成添加事件处理程序,也没有什么好的办法得到它与动态添加元素的工作。你必须修改插件,因此,它会知道,或许可选,动态应用的处理程序。这是工作了相当多的。一个更简单的方法是抽象的处理器成一个函数,然后将其应用到原始的元素和每一个新元素添加后,或许在回调

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

这篇关于jQuery的:使用自动完成()输入中的元素添加到页面的DOM加载后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:27