使用jQuery显示动态内容

时间:2013-02-14 12:52:57

标签: jquery css html

我有一个有序的链接列表,我希望在点击时显示它下面的内容,然后在点击其他链接时折叠。 这就是我到目前为止所做的。显示器有异常。 jsfiddle

<html>
<head>
<title>Jquery Change content of Div</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript" language="javascript"> 

jQuery(document).ready(function(){
        var $j = jQuery;    


$j('.biocontent div:not(:first-child)').hide();
$j('.services li a').click(function(){
    var showclass = $j(this).attr('class');
    $j('.biocontent div').fadeOut('fast',function(){
        $j('.biocontent div.' + showclass).show();
        });
});
});
</script>
</head>
<body>
<ul class="services">
<li><a class="div1" href="#"><h2>Div 1</h2></a></li>
<div class="biocontent ">
<div class="div1">
<p>Content1</p>
</div>
</div>

<li><a class="div2" href="#"><h2>Div 2</h2></a></li>
<div class="biocontent ">
<div class="div2">
<p>Content 2</p>
</div>
</div>

<li><a class="div3" href="#"><h2>Div 3</h2></a></li>
<div class="biocontent ">
<div class="div3">
<p>Content 3</p>
</div>
</div>

<li><a class="div4" href="#"><h2>Div 4</h2></a></li>
<div class="biocontent ">
<div class="div4">
<p>Content 4</p>
</div>
</div>

 <li><a class="div5" href="#"><h2>Div 5</h2></a></li>
<div class="biocontent>
<div class="div5">
Content 5
</div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这是解决方案:

<html>
<head>
<title>Jquery Change content of Div</title>
<style>
.servicescontent div{
    display:none;
}
</style>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript" language="javascript"> 
jQuery(document).ready(function(){
        var $j = jQuery;    

//services page
$j('.services li a').click(function(){
    var  showid= $j(this).attr('class');
    $j('.servicescontent div').hide();
   $('#'+showid).toggle('fast');
});
});
</script>
</head>
<body>
<ul class="services">
<li><a class="div1" href="#"><h2>Div 1</h2></a></li>
<div class="servicescontent">
<div id="div1" class="cont">
<p>Content1</p>
</div>
</div>

<li><a class="div2" href="#"><h2>Div 2</h2></a></li>
<div class="servicescontent">
<div id="div2"  class="cont">
<p>Content 2</p>
</div>
</div>

<li><a class="div3" href="#"><h2>Div 3</h2></a></li>
<div class="servicescontent">
<div id="div3"  class="cont">
<p>Content 3</p>
</div>
</div>

<li><a class="div4" href="#"><h2>Div 4</h2></a></li>
<div class="servicescontent">
<div id="div4"  class="cont">
<p>Content 4</p>
</div>
</div>

 <li><a class="div5" href="#"><h2>Div 5</h2></a></li>
<div class="servicescontent">
<div id="div5"  class="cont">
Content 5
</div>
</div>
</body>
</html>

答案 1 :(得分:1)

你的HTML搞砸了,所以我删除了一个额外的div.servicescontent并重写了该函数来切换内容 - http://jsfiddle.net/CCa7K/2/

$('a').click(function() {
    $(this).parent().next('.servicescontent').toggle();
});