Jquery:在加载 DOM 后对添加到页面的输入元素使用 autocomplete()
我正在使用这个与 Jquery 一起使用的自动完成插件: jQuery Autocomplete Mod
您可以通过以下方式使用它简单添加 $("selector").autocomplete(url [, options]);
页面加载时有 5 个输入元素(id = 通道后跟一个数字),这就是我使用此代码在每个输入上初始化自动完成插件的原因:
$(document).ready(function() {
$('input[id^="channel"]').each(function(){
$(this).autocomplete(
"autocomplete/autocomplete.php",
{
some options that don't matter now I guess
}
);
});
});
但现在我还希望自动完成插件能够处理输入元素(相同的 id 语法) ),这些是在页面加载后通过调用 javascript 函数(通过单击链接)添加的。
我现在有 Jquery 的 live() 函数,但我只是不知道应该如何在这里使用它。
我确信有一个很好且简单的方法可以做到这一点,但我现在想不出正确的方法。
提前致谢!
菲尔
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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.