2017-06-30 115 views
-2

我想在jQuery中做一個ajax搜索欄。我在一個地方觸動過。我在一個大div元素內創建了動態div元素,意味着創建了與json響應一起的div。我想要在用戶輸入東西時遍歷div元素那麼它應該通過上下箭頭鍵來遍歷。如何遍歷div元素在jquery中的div元素?

<div class="comment"> 
     <div class="single" > 
      //this div is dynamically created with the information 
     </div> 
</div> 

我想突出div元素內的項目與鍵和鍵的幫助下。 什麼是可能的方式。我嘗試了2-3種方法,但沒有用。

編輯 這是我曾嘗試

$(document).ready(function(){ 
     $('#inputText').on('keydown',function(e){ 
     var $current=$('.comment>.single').first(); 
     $current.css('background-color','yellow'); 
     if(e.keyCode==40){ 
     var $nextDiv; 
     if($current.next().size==0){ 
      $nextDiv=$('.comment>.single').first(); 
      } 
     else 
      { 
      $nextDiv=$current.next(); 
      } 
      $current.css('background-color',''); 
      $nextDiv.css('background-color','yellow'); 
      $current=$nextDiv; 
     } 
     }); 
    }); 

謝謝您的幫助

+2

你試過的2-3種方法是什麼? –

+0

我曾嘗試使用過濾器,第一個功能。但我可以輕鬆地突出顯示2div和其餘div元素,但當用戶從輸入框中按下1次時,我在第一個div處被敲擊,然後它應該首先突出顯示,然後它應該移動休息。 – Andrew

+0

在這裏發佈你的代碼...沒有看到你想要做的事情,人們將無法提供幫助 –

回答

0

你沒有正確設置你當前的股利和未來DIV,你也沒有顯示出你的代碼向下箭頭

好吧,這裏是我爲你提供的一個jsFiddle

https://jsfiddle.net/fxabnk4o/1/

還需要檢查是否有您的div有黃色的底色,並相應地穿越

我已經通過所有類的「單」的元素循環有更好辦法做到這一點

var a = $('.single'); 
     for(var i = 0; i < a.length; i++) 
     { 
     if($(a[i]).css('backgroundColor') == "rgb(255, 255, 0)") 
     { 
     isFirst = false; 
      $current= $(a[i]); 
      break; 
     } 
     else{ 
     isFirst = true; 
     $current = $('.comment > .single').first(); 
     } 
     } 

,然後根據旁邊的箭頭選擇壓制或前一個元素

if($current.next().size==0){ 
      $nextDiv=$('.comment>.single').first(); 
      } 
      if(!isFirst){ 
      $nextDiv=$current.next(); 
      $current.css('background-color',''); 
      $nextDiv.css('background-color','yellow'); 
      $current=$nextDiv; 
      } 
      else 
      { 
      $current.css('background-color','yellow'); 
      } 

and

var $nextDiv; 
     if($current.prev().size==0){ 
      $nextDiv=$('.comment>.single').first(); 
      } 
      if(!isFirst){ 
      $nextDiv=$current.prev(); 
      $current.css('background-color',''); 
      $nextDiv.css('background-color','yellow'); 
      $current=$nextDiv; 
      } 
      else 
      { 
      $current.css('background-color','yellow'); 
      } 
+0

非常感謝我找到了錯誤。 – Andrew

+0

如果您發現這是正確的,您可以將其標記爲答案。 –

+0

我有一個疑問,當我去(你的情況)後4鍵下,然後在第5鍵它不會突出顯示任何東西,而應該突出第一個鍵(第一格)。 – Andrew

0
$('input', $('#comment')).each(function() { 

$('input', $('#single')).each(function() { 

    console.log($(this)); //log every element found to console output 
}); 

    console.log($(this)); //log every element found to console output 
}); 
+0

我不想要所有的信息。我只想當用戶按下鍵,然後它應該突出最接近的div(只在下按鍵時突出顯示) – Andrew