更改后jQuery AutoComplete选择触发?

我正在使用jQuery UI AutoComplete控件 (刚刚更新到jQuery UI 1.8.1)。 每当用户离开文本框时,我想将文本框的内容设置为已知良好值,并为所选值设置隐藏ID字段。 此外,我希望页面在文本框的内容更改时回发。

目前,我通过让autocomplete select事件设置隐藏ID然后在文本框上设置更改事件来设置文本框值,并在必要时导致回发来实现此function。

如果用户只使用键盘,这可以很好地工作。 您可以键入,使用向上和向下箭头选择值,然后使用Tab键退出。 触发select事件,设置id,然后触发change事件并返回页面。

如果用户开始输入然后使用鼠标从自动完成选项中选择,则更改事件将触发(当焦点转移到自动完成菜单?)并且页面在select事件有机会设置ID之前发回。

有没有办法让更改事件在select事件之后才会触发,即使使用鼠标也是如此?

$(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()函数。

您可以在自动完成演示和文档页面上查看事件列表。 它声明change事件总是在close事件之后触发,我认为这是在select事件之后触发的。 看一下’combobox’的来源,看看一个示例更改事件挂钩。

当我这样做时,它对鼠标选择有用:

 focus: function (event, ui) { $j(".tb").val(ui.item.value); return true; } 

这会导致TextBox文本在鼠标焦点事件上发生更改,就像它在键盘事件上发生的那样。 当我们选择一个项目时,它会触发选择更改。

我不知道阻止更改事件被触发,但您可以轻松地在更改事件中抛出一些条件,以确保已设置隐藏字段并且TextBox当前具有值。