如何在jquery中遍历div元素中的div元素?

时间:2017-06-30 18:36:52

标签: java jquery html css

我试图在jquery中创建ajax搜索栏。我在一个地方被击中。我在一个大div元素中创建了动态div元素,意味着div与json响应一起创建。我想在用户输入后遍历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 个答案:

答案 0 :(得分: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
});

答案 1 :(得分:0)

您没有正确设置当前div和下一个div,也没有显示您的箭头代码

这里有一个我为你提供的jsFiddle

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

你还需要检查你的div是否有背景颜色为黄色并相应地遍历

我使用'.single'类循环遍历所有元素,有更好的方法来做到这一点

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'); 
          }

 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'); 
          }
相关问题