gpt4 book ai didi

javascript - 具有相同源的多个字段的 jQuery 自动完成 - 简单功能

转载 作者:行者123 更新时间:2023-11-28 08:08:03 27 4
gpt4 key购买 nike

我正在一个js文件中开发一个函数prepareAutocomplete(path, idArray),该函数在我的整个应用程序中都可用。因此,每当我希望某个字段具有自动完成功能时,它就会如下所示:

HTML:

<input type="text" id="employee_list" />
<input type="hidden" id="employee" />

您将在文本字段中输入内容,如果您从自动完成列表中选择结果,则其值将保存在隐藏字段中。

您可以将自动完成功能绑定(bind)到此字段,如下所示:

prepareAutocomplete("path/to/script/that/returns/results", 
['listID' => 'employee_list', 'hiddenID' => 'employee']);

我的 prepareAutocomplete - 函数现在看起来像这样:

var autoCompleteItemsLoaded = [];   

function prepareAutocomplete(path, idArray){
// first checking if data has been fetched from database before
if(!(path in autoCompleteItemsLoaded)){
// if not, get the data from the database
$.ajax({
url: path,
dataType: 'json',
async: false,
success: function(data) {
var items = [];

data.forEach(function(item){
items.push({label: item["name"], value: item["id"]}); // store data in items-array
});

autoCompleteItemsLoaded[path] = items; // store items-array in array that has all loaded items
}
});
}

var items = autoCompleteItemsLoaded[path];

for(var key in idArray){
$('#'+idArray[key].listID).autocomplete({
source: items,
messages: {
noResults : '',
results: function(){}
},
select: function(event, ui){
this.value = ui.item.label;
return false;
},
change: function(event, ui){
if(this.value == '' || this.value == null){
$("#"+idArray[key].hiddenID).val('');
}else if(ui.item != null){
$("#"+idArray[key].hiddenID).val(ui.item.value);
}
}
});
}
}

现在,如果 idArray 中只有一个字段,则此代码可以工作。但是,一旦我使用 idArray 中的多个字段,例如,如果我在同一页面上有多个员工字段(当然具有不同的 ID!),它就不会按其应有的方式工作。它在每个字段中显示自动完成内容,这是正确的,但如果您选择一个结果,则 idArray 中 LAST 字段的值会更改!

我不明白为什么。有人可以帮助我吗?

最佳答案

prepareAutocomplete("path/to/script/that/returns/results",
['listID' => 'employee_list', 'hiddenID' => 'employee']);
我不确定我是否理解您的意思 ['listID' => 'employee_list', 'hiddenID ' => '员工']。我认为您的意思是编写 [{'listID': 'employee_list', 'hiddenID': 'employee'}] 这意味着根据您的设计,如果您想使用多个 自动完成功能 绑定(bind),您必须按如下方式调用该函数:

prepareAutocomplete("path/to/script/that/returns/results",
[{'listID': 'employee_list1', 'hiddenID': 'employee1'},
{'listID': 'employee_list2', 'hiddenID': 'employee2'},
{'listID': 'employee_list3', 'hiddenID': 'employee3'}]);

那么你的 for 循环需要一个闭包,如下所示:

for(var key in idArray){
(function( arr ) {
$('#' + arr.listID).autocomplete({
source: items,
messages: {
noResults : '',
results: function(){}
},
select: function(event, ui){
this.value = ui.item.label;
return false;
},
change: function(event, ui){
if(this.value == '' || this.value == null){
$("#" + arr.hiddenID).val('');
}else if(ui.item != null){
$("#" + arr.hiddenID).val(ui.item.value);
}
}
});
})( idArray[key] );
}

关于javascript - 具有相同源的多个字段的 jQuery 自动完成 - 简单功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595655/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com