用于动态创建的输入的 jQuery 自动完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2663573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery autocomplete for dynamically created inputs
提问by Jamatu
I'm having an issue using jQuery autocomplete with dynamically created inputs (again created with jQuery). I can't get autocomplete to bind to the new inputs.
我在使用 jQuery 自动完成和动态创建的输入(再次使用 jQuery 创建)时遇到问题。我无法自动完成以绑定到新输入。
Autocomplete
自动完成
$("#description").autocomplete({
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
});
New table row with inputs
带有输入的新表格行
var i = 1;
var $table = $("#works");
var $tableBody = $("tbody",$table);
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" id="description" name="item[' + i + '][works_description]" /></td></tr>');
$tableBody.append(newtr);
i++;
});
I'm aware that the problem is due to the content being created after the page has been loaded but I can't figure out how to get around it. I've read several related questions and come across the jQuery live method but I'm still in a jam!
我知道问题出在页面加载后创建的内容,但我不知道如何解决它。我已经阅读了几个相关的问题并遇到了 jQuery live 方法,但我仍然陷入困境!
Any advice?
有什么建议吗?
回答by Z. Zlatev
First you'll want to store the options for .autocomplete()
like :
首先,您需要存储.autocomplete()
like的选项:
var autocomp_opt={
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
};
It's more neat to use the class
attribute for marking the input
, like:
使用class
属性来标记更简洁input
,例如:
<input type="text" class="description" name="item[' + i + '][works_description]" />
Last, when you create a new table row apply the .autocomplete()
with the options already stored in autocomp_opt
:
最后,当你创建一个新的表行时,应用.autocomplete()
已经存储在的选项autocomp_opt
:
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>');
$('.description', newtr).autocomplete(autocomp_opt);
$tableBody.append(newtr);
i++;
});
回答by Alex
I found that I needed to put teh autocomplete after the append so:
我发现我需要在追加之后放置自动完成功能,所以:
$tableBody.append(newtr);
$('.description', newtr).autocomplete(autocomp_opt);