2017-03-06 18 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/