我的要求是,当用户在可能也会动态添加的输入字段之一中输入一些字符(最少3个)时,显示几个选项。
由于数据量巨大,我一开始无法在页面加载时加载数据。有一个ajax调用来获取经过过滤的数据。
我得到的问题是Expected identifier第2行的页面加载错误。那么,请问以下代码有什么问题吗?
Expected identifier
$(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 });
如何使用另一种方法:创建输入时初始化自动完成功能:
$(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>
jsFiddle与AJAX