有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图在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) 个答案

  1. # 1 楼答案

    $('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
    });
    
  2. # 2 楼答案

    您没有正确设置当前div和下一个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'); 
              }
    

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