用于动态创建输入的 jQuery 自动完成
我在使用 jQuery 自动完成功能和动态创建的输入(再次使用 jQuery 创建)时遇到问题。我无法将自动完成功能绑定到新输入。
自动完成
$("#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,
});
带有输入的新表格行
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++;
});
我知道问题是由于页面加载后创建的内容造成的,但我不知道如何解决它。我已经阅读了几个相关问题并遇到了 jQuery live 方法,但我仍然陷入困境!
有什么建议吗?
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.
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!
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您需要存储
.autocomplete()
的选项,例如:使用
class
属性来标记input
会更简洁,例如:最后,当您创建新表行时,应用
.autocomplete()
以及已存储在autocomp_opt
中的选项:First you'll want to store the options for
.autocomplete()
like :It's more neat to use the
class
attribute for marking theinput
, like:Last, when you create a new table row apply the
.autocomplete()
with the options already stored inautocomp_opt
:我发现我需要将自动完成功能放在附加后面,因此:
I found that I needed to put teh autocomplete after the append so: