我是jquery的新手
我使用了http://jqueryui.com/autocomplete/#maxheight
正常情况下工作正常。对于动态创建的字段,
我使用(on
和live
方法)
$(".searchInput").on("keydown.autocomplete", function() {
source: availableTags
});
但它也不适用于静态字段......
以下是我的代码
脚本:
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$(".searchInput").on("keydown.autocomplete", function() {
source: availableTags
});
});
$( "#tag2" ).blur(function() {
$('#myTabContent').append(
'<input id="field" name="tags[]" type="text" class="searchInput" />');
});
HTML:
<div id="myTabContent" class="tab-content">
<form role="form" class="add_client_popup">
<input type="text" id="tags" name="tags[]" class="searchInput" >
<div class="liner"></div>
<input type="text" id="tags1" name="tags[]" class="searchInput" >
<div class="liner"></div>
<input type="text" id="tag2" name="tags[]" class="searchInput" >
</form>
</div>
我在这里做错了什么。请帮我。
答案 0 :(得分:0)
只要您追加.searchInput
,就可以调用autocomplete
函数
$('#myTabContent').append(
'<input id="field" name="tags[]" type="text" class="searchInput" placeholder="Autocomplete" />');
$(".searchInput").autocomplete({
source: availableTags
});
答案 1 :(得分:0)
一个很常见的错误是将事件附加到尚不存在的元素上。
解决这个问题的一种方法是将事件附加到父元素,遵循一个简短的例子
<div id="container">
<a id="existing" href="#">test</a>
</div>
$('a#existing').on('click', function(){
$('#container').append('<input id="appended" type="text"/>');
// here we would instanciate autocompleter btw
$('#appended').autocomplete({
source: availableTags
});
});
// in this case using
// $('#appended').on('keydown', ... doesnt'work
// because #appended is not part of the dom
// following should work
// using .one() to detach after first event
$('#container').one('keydown.myEvent', 'input#appended', function(){
// do something .. for example set autocomplete source ;)
// from jqueryui api http://api.jqueryui.com/autocomplete/#option-source
// setter
$('input#appended').autocomplete( "option", "source", anotherSource );
});