2012-08-07 84 views
2

我已经实现了AJAX搜索这是类似的例子here。在本例中,您可能会注意到,您可以使用TAB键在搜索结果之间切换。在我的搜索结果中,存在以下格式的表:键盘友好AJAX搜索

*Client* *Status* *Hostname* 
<client1> value  value 
<client2> value  value 
<client3> value  value 

Client1, client2, client3实际上是超链接,并在课堂上search_result_entry。所以,当按下向下箭头键时,我希望焦点转到client1链接。 TAB键在这里工作,但方向键会更直观。状态和主机名中的值不可点击。另外请注意,我使用的是overflow: auto,所以如果搜索结果太多,滚动条就会显示出来。在这种情况下,按两次TAB键会将我转到第一个搜索结果。

我做的摸索与尝试下面的代码,但它没有工作:

if (e.which == 40){ // 40 is the ASCII for down arrow key 
    $("#keyword").focusout(); 
    $("#results").focus(function(){ 
      $(this).next("td").focus(); 
    }); 
} 

如何获得重点使用向下箭头键移动到搜索结果中,并在其中导航使用向下/向上箭头键?

+0

你可以在jsfiddle.com上发布你的代码 – 2012-08-07 14:41:22

回答

2
//Keep track of the focused element 
var focusedElement = null; 

// update it on focus 
$("#results").focus(function(){ 
    focusedElement = this; 
}); 

和地方在你的处理器:

//... code 
if (e.which == 40){ // 40 is the ASCII for down arrow key 
    if(focusedElement) $(focusedElement).next().focus(); 
    else $('#results').somethingToGetYourFirstElementDependingOnYourCode().focus(); 
} 
//... more code 

,第一部分将跟踪当前聚焦元素(如果有的话),第二部分将更新聚焦元素(这将触发第一部分和更新当前集中的元素)

+0

对不起,这个工作适合我。我将你的代码放置在我正在实现搜索功能的onkeyup事件中。然而,它力道通过。 – 2012-08-07 14:59:45