2012-10-16 68 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