2012-09-07 45 views
1

相关李我有一个列表:显示根据所选李

<ul class="products"> 
    <li class="products p1">first</li> 
    <li class="description p1">first</li> 
    <li class="products p2">second</li> 
    <li class="description p2">second</li> 
    <li class="products p3">third</li> 
    <li class="description p3">third</li> 
    <li class="products p4">fourth</li> 
    <li class="description p4">fourth</li> 
</ul> 

,我想使用jQuery:
当用户点击一个除了点击一个1隐藏其他利秒。
2当用户再次点击活动的li时显示所有的li。
我用下面的脚本:

$(window).load(function(){ 
$(".products li").click(function(){ 
    if ($(this).hasClass("active")) { 
      $(".products li").show("slow"); 
      $(this).removeClass("active"); 
    } else { 
      $(this).addClass("active"); 
      $(".products li:not(.active)").hide("slow"); 
    } 
}); 
}); 

它工作正常。
现在我想要显示活动li的相关描述li。
例如,如果所述活性锂与类中的力:P2,然后下面的描述里需要被示出和李水净化就去隐藏:

<li class="description p2">second</li> 

说明李s的开头隐藏。
我不知道如何根据类名选择正确的li。应该有一个jQuery技巧,通过带有掩码的类名来选择li!

回答

1

添加.active类下一li$(this).next().addClass("active");),也改变选择到li.products因为所有li可点击:

$(window).load(function(){ 
    $(".products li.products").click(function(){ 
     if ($(this).hasClass("active")) { 
       $(".products li").show("slow"); 
       $(this).removeClass("active"); 
       $(this).next().removeClass("active"); 
     } else { 
       $(this).addClass("active"); 
       $(this).next().addClass("active"); 
       $(".products li:not(.active)").hide("slow"); 
     } 
    }); 
}); ​​ 

JSFiddle Example

0

尝试使用.next() jQuery的功能。由于描述始终是活动元素的下一个li元素,因此您应该能够获得下一个兄弟并使用.show()

.next(): 

Get the immediately following sibling of each element in the set of matched elements. If a 
selector is provided, it retrieves the next sibling only if it matches that selector. 

http://api.jquery.com/next/