如何将 jquery ui 自动完成添加到动态创建的元素?
我试图让 jQueryUI AutoComplete 在动态创建的表单输入元素上触发,但它不起作用。我尝试过使用 keyup.autocomplete 和 keydown.autocomplete 作为 $.live() 中的绑定事件,但它绑定到新元素 - 仅限于页面上已有的元素。
尝试此处的代码(尝试在第一个输入中键入“ava”,然后单击“添加输入” " 并在新输入中键入相同的内容)。
JavaScript:
$(function() {
$("input#addButton").click(function() {
$("input.searchInput:last").clone(true).appendTo($(this).closest("form"));
$("input.searchInput:last").val("");
})
$("input.searchInput").live("keydown.autocomplete", function() {
$(this).autocomplete({
source: [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
],
minLength: 2
});
})
});
HTML:
<form name="myForm" method="post">
<input id="addButton" name="addButton" type="button" value="Add an input" />
<input name="search" value="" class="searchInput" maxlength="20" />
</form>
I'm trying to get jQueryUI AutoComplete to trigger on dynamically created form input elements, but it's not working. I've tried using keyup.autocomplete and keydown.autocomplete as bind events in $.live(), but it's binding to the new elements - only those already on the page.
Try out the code here (try typing "ava" in the first input, then click "Add an Input" and type the same in the new input).
JavaScript:
$(function() {
$("input#addButton").click(function() {
$("input.searchInput:last").clone(true).appendTo($(this).closest("form"));
$("input.searchInput:last").val("");
})
$("input.searchInput").live("keydown.autocomplete", function() {
$(this).autocomplete({
source: [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
],
minLength: 2
});
})
});
HTML:
<form name="myForm" method="post">
<input id="addButton" name="addButton" type="button" value="Add an input" />
<input name="search" value="" class="searchInput" maxlength="20" />
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果有人仍然需要,当新创建的输入获得焦点时,此代码将触发自动完成:
In case somebody still need, this code will trigger autocomplete when new created input get focus:
函数 .live() 现已弃用。
看起来像这样的代码有效:
Function .live() is deprecated now.
Looks like code like this works:
这有效:
This works: