使用动态添加的元素在 jQuery 中自动完成 [英] AutoComplete in jQuery with dynamically added elements
本文介绍了使用动态添加的元素在 jQuery 中自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的要求是当用户在输入字段之一中输入一些字符(最少 3 个)时显示几个选项,这些字符也可能是动态添加的.
My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
一开始我无法在页面加载时加载数据,因为数据很大.有一个 ajax 调用来获取过滤后的数据.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
我遇到的问题是页面加载第 2 行时出现 Expected identifier
错误.那么,您能告诉我下面的代码有什么问题吗?
The issue what I am getting is Expected identifier
error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
推荐答案
如何使用另一种方法:在创建输入时初始化自动完成:
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
这篇关于使用动态添加的元素在 jQuery 中自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文