发帖回答我自己的问题:
我有以下HTML:
<select id="genre-select">
<option value="-1">Make a selection</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input id="band-input" type="text" />
<button id="go-button">Go</button>
<button>Unrelated Button</button>
我正在使用jquery-ui自动完成对象,我的原始javascript看起来像:
var bandValue = "-1";
var $genreSelect = $("#genre-select");
var $bandInput = $("#band-input");
var $goButton = $("#go-button");
var bands = [
{
value: "1",
label: "AC/DC",
desc: "..."
},
{
value: "2",
label: "Black Sabbath",
desc: "Ozzy Osbourne, Tony Iommi, Bill Ward, etc."
},
{
value: "3",
label: "Cars, The",
desc: "..."
}
];
$bandInput.autocomplete({
source: bands,
focus: function( event, ui ) {
$bandInput.val( ui.item.label );
return false;
},
select: function( event, ui ) {
console.log("select event");
bandValue = ui.item.value;
$bandInput.val(ui.item.label);
return false;
}
});
然而,当使用键盘导航并按TAB时,焦点将跳转到“无关按钮”而不是预期的“开始”按钮。我试图吞下所有的按键和点击事件,并完全控制$ goButton何时获得焦点,没有任何效果。
答案 0 :(得分:0)
经过大量的故障排除后,解决方案实际上非常简单。如果autocomplete.select事件来自TAB,我只是跳过调用 $ goButton.focus(),并允许常规事件完成它的工作。
$bandInput.autocomplete({
source: bands,
focus: function( event, ui ) {
$bandInput.val( ui.item.label );
return false;
},
select: function( event, ui ) {
bandValue = ui.item.value;
$bandInput.val(ui.item.label);
if(event.which != null){
if(event.which != 9){
//it's not a tab, so focus
$goButton.focus();
}
else {
//already going to focus, so don't create race condition
}
}
return false;
}
});