如何将自动完成功能与事件绑定结合使用?
我有一个表单,可以在其中添加具有自动完成功能的字段。
是否可以使用事件绑定来添加自动完成功能,而不是在创建每个字段时将自动完成功能添加到每个字段?
对于 Javascript 中的事件,我是新手。
这就是我使用事件绑定添加新行的方法(完美运行):
$(function() {
$('input[name=addItem]')
.bind('click', function() {
var line = $('#list > div').size()+1;
divId = 'line-'+line;
var divCloned = $('#line-1').clone();
divCloned.attr('id', divId);
$('#list').append(divCloned);
var inputs = $(divCloned).children('input').get();
for (var i in inputs) {
inputs[i].value='';
inputs[i].id = inputs[i].id.replace(/\d+/, line);
inputs[i].name = inputs[i].name.replace(/\d+/, line);
}
this.blur();
});
});
I have a form where I can add fields that have autocomplete.
Instead of adding the autocomplete to each field as I create them, is it possible to use event binding to add the autocomplete?
I am new when it comes to events in Javascript.
This is what I have done to add a new line, using event binding (works perfectly):
$(function() {
$('input[name=addItem]')
.bind('click', function() {
var line = $('#list > div').size()+1;
divId = 'line-'+line;
var divCloned = $('#line-1').clone();
divCloned.attr('id', divId);
$('#list').append(divCloned);
var inputs = $(divCloned).children('input').get();
for (var i in inputs) {
inputs[i].value='';
inputs[i].id = inputs[i].id.replace(/\d+/, line);
inputs[i].name = inputs[i].name.replace(/\d+/, line);
}
this.blur();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解您的问题,您希望将自动完成功能应用于所有输入字段吗?您可以通过概括选择器来做到这一点,而不是将事件添加到
$('input[name=addItem]')
(含义:对于具有属性“name”的“input”类型的所有标签" 设置为 "additem") 例如,您可以使用$('input[type=text]')
,它将您的事件绑定到属性“type”设置为“text”的所有输入标签。根据您的应用程序,您是否想要根据单击的输入字段更改建议的自动完成功能?这需要在事件处理程序中添加更多逻辑。
If I understand your question correctly, you want your autocomplete to be applied to all input fields? You can do that by generalizing your selector, so instead of adding the event to
$('input[name=addItem]')
(Meaning: To all tags of type "input" with an attribute "name" set to "additem") you can for example use$('input[type=text]')
which will bind your event to all input-tags with attribute "type" set to "text".Depending on your application, would you want to change the suggested auto-completes based on which input-field is being clicked on? That'd need more logic in your event handler.
选项1:复制原始自动完成
您可以制作
.clone ()
,包括使用.clone(true)
的事件处理程序:这应该包括
#line-1
的自动完成,因此,通过上面的行替换代码中的相应行,您应该已经准备就绪。选项 2:创建具有不同选项的新自动完成功能
如果您想更改自动完成功能,只需重新设置即可:
Option 1: Copy the original autocomplete
You can make a
.clone()
that includes event handlers using.clone(true)
:This should include the autocomplete for
#line-1
, so with the line above replacing the corresponding line in your code you should be all set.Option 2: Create a new autocomplete with different options
If you want to change the autocomplete functionality, you can just set it again: