Ajax 加载内容上的 JQuery 自动完成
我想在使用 Ajax 加载的输入框中使用 JQuery 的自动完成插件:
我尝试使用以下代码来实现这一点,但是它仅在用户单击输入两次时才有效:
$(document).ready(function() {
$('#auto').live('keydown', function(){
$(this).autocomplete(
"/autocomplete",
{
delay:10,
minChars:2,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:selectItem,
formatItem:formatItem,
autoFill:true
});
});
});
您能告诉我是否有问题吗用我的代码?
谢谢,
I would like to use the JQuery's autocomplete plugin on a input box loaded using Ajax:
I have tried to achieve that using the following code, however it only works when the users clicks twice into the input :
$(document).ready(function() {
$('#auto').live('keydown', function(){
$(this).autocomplete(
"/autocomplete",
{
delay:10,
minChars:2,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:selectItem,
formatItem:formatItem,
autoFill:true
});
});
});
Could you tell me if there is something wrong with my code?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所给出的解决方案有一个问题。
它只在第二个字符之后执行自动完成,因为第一个字符不能用于自动完成查询,因此这是触发
keydown
并执行自动完成控件注册的字符。以下代码附加到所有(匹配的)现有和新创建的 (Ajax) 元素的
focus
事件,并在您单击或按 Tab 键进入输入后执行autocomplete()
注册:在此例如,选择器查找具有属性
“data-autocomplete”
的所有元素,相同的属性用作源 url:Importarnt:
根据版本的不同,您可以首先使用
live()
、delegate()
或on()
函数。这三个的签名略有不同,但很容易弄清楚它们如何相互映射:The solution given in question had one issue.
It executes auto-complete only after second character, because the first character can not be used for auto-complete query, thus this is the one which triggers
keydown
and executes registration of the control for auto-complete.Following code attaches to all (matching) existing and newly created (Ajax) element's
focus
event, and performsautocomplete()
registration after you click or tab into the input:in this example the selector find all elements having attribute
"data-autocomplete"
, the same attribute is used as source url:Importarnt:
Depending on version you could use either
live()
,delegate()
oron()
function at the first place. Signatures of these three are slightly different, but it's quite easy to figure out how they map to each other:});
以上对我有用...
});
Above worked for me...
我不确定,但我认为您的示例中的 live() 函数将绑定 keydown 事件,以便它仅在您触发它后才应用自动完成功能。尝试跳过 live() 并仅使用自动完成:
I'm not sure, but I think the live()-function in your example will bind the keydown-event so that it applies the autocomplete only after you've triggered it. Try skipping the live() and go with only the autocomplete: