在jquery中查找当前可见的div

我有四个div所有设置display:none和文件。我正在显示第一个div ..我有4个链接按钮link1,link2 … link4 …我在link1点击上显示div1等等..如何找到当前在jquery中可见的div?

   .ContentDivs { width: 90%; height: 300px; border: solid 5px #404040; display:none; }    
DIv1
Div2
Div3
Div4
$(document).ready(function() { $("#div1").show().fadeIn("slow"); }); $('#Link1').click(function() { $(".ContentDivs").fadeOut("fast");//find current div here? $("#div1").show().fadeIn("slow"); }); $('#Link2').click(function() { $(".ContentDivs").fadeOut("fast");//find current div here? $("#div2").show().fadeIn("slow"); }); $('#Link3').click(function() { $(".ContentDivs").fadeOut("fast");//find current div here? $("#div3").show().fadeIn("slow"); }); $('#Link4').click(function() { $(".ContentDivs").fadeOut("fast");//find current div here? $("#div4").show().fadeIn("slow"); });

在http://jsbin.com/umode4/edit上查看效果

用较小的代码,你可以这样做…

jQuery的

  

HTML

 
DIv1
Div2
Div3
Div4

演示

您可以使用:visiblefilter选择器。

 $('.ContentDivs:visible')......... 

更新:

一种更简单的方法是为每个链接提供一个rel属性,其值与div和一个类的id相同,例如:

 Link1 Link1 

和div:

 
Div1
Div2

然后你需要的是获得点击链接的rel并显示/隐藏相应的div:

 $('a.link').click(function(){ var rel = $(this).attr('rel'); if ($('div#' + rel).is(':visible')) { $('div#' + rel).fadeOut('fast'); } else { $('div#' + rel).fadeIn('fast'); } return false; }); 

尝试

 var displayedDiv = $('div.ContentDivs').filter(':visible'); 

甚至这个

  var displayedDiv = $('div.ContentDivs').filter(function(){ if($(this).css('display') != 'none') return true; else return false; }); 

使用

 $(".ContentDivs:visible"); 

这应该工作:

HTML

 
DIv1
Div2
Div3
Div4

使用Javascript

 $(function () { $("#links a").click( function () { $(".ContentDivs").css( "display", "none"); $("#"+this.rel+".ContentDivs").fadeIn(); }); });