我正在使用 jQuery UI AutoComplete control (刚刚更新到 jQuery UI 1.8.1)。每当用户离开文本框时,我想将文本框的内容设置为一个已知的正确值,并为所选的值设置一个隐藏的 ID 字段。此外,我希望页面在文本框的内容发生更改时回发。
目前,我通过让自动完成选择事件设置隐藏 ID,然后在文本框上设置文本框值并在必要时引起回发的更改事件来实现此目的。
如果用户只使用键盘,这将非常有效。您可以键入,使用向上和向下箭头选择一个值,然后按 Tab 键退出。 select 事件触发,id 被设置,然后 change 事件触发,页面回发。
如果用户开始输入然后使用鼠标从自动完成选项中选择,更改事件将触发(当焦点转移到自动完成菜单时?)并且页面在选择事件有机会设置身份证。
有没有办法让 change 事件在选择事件之后才触发,即使使用鼠标也是如此?
$(function() {
var txtAutoComp_cache = {};
var txtAutoComp_current = { label: $('#txtAutoComp').val(), id: $('#hiddenAutoComp_ID').val() };
$('#txtAutoComp').change(function() {
if (this.value == '') { txtAutoComp_current = null; }
if (txtAutoComp_current) {
this.value = txtAutoComp_current.label ? txtAutoComp_current.label : txtAutoComp_current;
$('#hiddenAutoComp_ID').val(txtAutoComp_current.id ? txtAutoComp_current.id : txtAutoComp_current);
} else {
this.value = '';
$('#hiddenAutoComp_ID').val('');
}
// Postback goes here
});
$('#txtAutoComp').autocomplete({
source: function(request, response) {
var jsonReq = '{ "prefixText": "' + request.term.replace('\\', '\\\\').replace('"', '\\"') + '", "count": 0 }';
if (txtAutoComp_cache.req == jsonReq && txtAutoComp_cache.content) {
response(txtAutoComp_cache.content);
return;
}
$.ajax({
url: 'ajaxLookup.asmx/CatLookup',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonReq,
type: 'POST',
success: function(data) {
txtAutoComp_cache.req = jsonReq;
txtAutoComp_cache.content = data.d;
response(data.d);
if (data.d && data.d[0]) { txtAutoComp_current = data.d[0]; }
}
});
},
select: function(event, ui) {
if (ui.item) { txtAutoComp_current = ui.item; }
$('#hiddenAutoComp_ID').val(ui.item ? ui.item.id : '');
}
});
});
最佳答案
您可以通过将更改事件实现为自动完成选项来解决此问题,就像选择一样,而不是使用 jQuery 的 change() 函数。
您可以在 the autocomplete demo & documentation page 查看事件列表.它指出 change 事件总是在 close 事件之后触发,我认为它是在 select 事件之后触发的。查看“combobox”的源代码以查看示例更改事件 Hook 。
关于javascript - jQuery 自动完成选择更改后触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2870077/