2017-03-06 44 views
0

我试图根据nth-child或基于计数的选择器做出一些隐藏显示项。 如果我点击第一行的第一个项目,那么第二行的第一个项目应该显示,并且该行中的其他项目应该隐藏。请帮助简化代码。基于子nth的子类隐藏显示在多行中

$(document).ready(function(){ 

    $(".subrow1 .item-a a:nth-child(1)").click(function(){  
     $(".subrow2 .idgroupsub:nth-child(1)").show(); 
     $(".subrow2 .idgroupsub:nth-child(2)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(3)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(4)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(5)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(6)").hide(); 
    }); 
    $(".subrow1 .item-a a:nth-child(2)").click(function(){  
     $(".subrow2 .idgroupsub:nth-child(2)").show(); 
     $(".subrow2 .idgroupsub:nth-child(1)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(3)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(4)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(5)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(6)").hide(); 
    }); 

    $(".subrow1 .item-a a:nth-child(3)").click(function(){  
     $(".subrow2 .idgroupsub:nth-child(3)").show(); 
     $(".subrow2 .idgroupsub:nth-child(1)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(2)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(4)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(5)").hide(); 
      $(".subrow2 .idgroupsub:nth-child(6)").hide(); 
    }); 

}); 

http://jsfiddle.net/Lv5cn8xy/244/

+0

https://api.jquery.com/ index /,https://api.jquery.com/eq/ – CBroe

回答

0

我已经更新了小提琴。请查看:http://jsfiddle.net/Lv5cn8xy/245/让我知道它是否有帮助。我为你的按钮添加了一个额外的属性,并编写了下面的jQuery。

$(document).ready(function(){ 
    $(".subrow1 .item-a a").click(function(){ 
     var show_div = $(this).attr('show'); 
     $('.idgroupsub').each(function(){ 
      $(this).hide(); 
     }); 
     $('.idgroupsub.item-'+show_div).show(); 
    }); 
}); 
0

你可以用 “指数()” 函数尝试一下,用CSS这样的选择:

$(document).ready(function(){ 

    $(".subrow1 .item-a a").click(function(){ 
     var index = $(this).index()+1; 
     $(".subrow2 .idgroupsub:nth-child("+index+")").show(); 
     $(".subrow2 .idgroupsub:not(:nth-child("+index+"))").hide(); 
    }); 

}); 

工作例如:http://jsfiddle.net/CodeFoxx/us1nk859/