2012-10-16 66 views
1

我遵循W3Schools教程进行AJAX实时搜索,并且它一直在正常工作。我将我的AJAX结果作为锚点元素返回。Ajax下拉键盘导航(上和下箭头)

我想为Ajax下拉菜单添加键盘导航(即向上箭头和向下箭头),而我最好的结果是将焦点放在仅停留一秒钟然后焦点消失的第一个结果上。我想知道为什么这个焦点消失了,以及以任何方式避开它。

我的JavaScript代码:

<script type="text/javascript"> 
    $(document).ready(function(){ 
     $('#searchInput').keyup(function(e){ 
      var keyCode = e.keyCode || e.which; 
      if (keyCode == 40){ 
       $('.hint').first().focus(); 
       $('.hint').first().css('color','#E8AE00'); //I can get the focus to here, but the focus will disappear right away. 
      } 
     }) 
    }) 
</script> 

这是我的PHP代码:

<?php 
    $q = $_GET["q"]; 
    $xmlDoc = new DOMDocument(); 
    $xmlDoc -> load("database.xml"); 
    $rest = $xmlDoc -> getElementsByTagName('restaurant'); 

    if (strlen($q)>0){ 
     $hint[] = ""; 
     $index = 0; 
     for ($i = 0; $i < ($rest->length); $i++){ 
      $name = $rest -> item($i) -> getElementsByTagName('name'); 
      $link = $rest -> item($i) -> getElementsByTagName('link'); 
      if ($name -> item(0) -> nodeType == 1){ 
       if (strtolower($q) == strtolower(substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q)))){ //if matching 
        $hint[$index] = "<a class='hint' id='hint".$index."' href='".$link -> item(0) -> childNodes -> item(0) -> nodeValue."' onfocus=\"this.style.color='#E8AE00'\">".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q))."<b>".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,strlen($q))."</b></a><br />"; 
        $index++; 
       } 
      } 
     } 
    } 

    if ($hint[0] == ""){ 
     echo "no suggestion"; 
    } 
    else { 
     for ($j = 0; $j < (count($hint)); $j++){ 
      echo $hint[$j]; 
     } 
    } 
?> 

感谢。

+0

你有没有其他方法运行后的密码?听起来好像另一个事件监听器或延迟的方法正在关注你的焦点。 – AMember

回答

0

可能是因为您打电话$('.hint').first().focus();而导致下拉列表正在消失,这会从(a.k.a模糊)#searchInput中盗取焦点。模糊输入,我想,隐藏下拉由于一些JS代码,你没有包括在这里,哪(正确)隐藏下拉。

我不确定为什么你甚至需要在提示上致电focus()

0

您正在构建带有焦点的内嵌javascript事件的链接,这看起来确实不重要?

<a class='hint' id='hint" ...... onfocus=\"this.style.color='#E8AE00'\">" 

另外,请注意您多次生成相同的ID?他们应该是唯一的!

如果您使用一些jQuery并创建委托鼠标事件,然后触发该事件而不是焦点事件,它应该很有可能工作?

$(function(){ 
    $(document).on({ 
     mouseenter: function() { 
      $(this).css('color', '#E8AE00') 
     } 
    }, '.hint'); 

    $('#searchInput').on('keyup', function(e){ 
      if (e.which == 40){ 
       $('.hint').first().trigger('mouseenter'); 
      } 
    }); 
}); 
+0

重复是我的错误。我一直在玩代码,一定忘记了它。关于ID,我实际上给它分配了一个数字变量:hint0,hint1,hint2,...。尽管'聚焦'对结果没有太大影响。 – mline86

+0

@ mline86 - >以下是我的做法:http://jsfiddle.net/BH8Hm/2/ – adeneo

+0

嗨,Adeneo,我试过了你的。它仍然没有解决焦点问题。焦点不断回到#searchInput。当我添加额外的行来模糊#searchInput时,焦点转到滚动条。 – mline86