using jquery to change visibility of divs with nes

2019-05-16 16:01发布

I have a list of links. When one of the links is clicked, I would like to change the visibility of the div associated with it. My html looks like the following:

<div id="tab">
<ul>
<li id="tab1" class="active"><a href="#">Link 1</a></li>
<li id="tab2"><a href="#">Link 2</a></li>
<li id="tab3"><a href="#">Link 3</a></li>
<li id="tab4"><a href="#">Link 4</a></li>
</ul>
</div>

<div id="content1"><div class="nestedDiv">Content Here</div></div>
<div id="content2"><div class="nestedDiv">Content Here</div></div>
<div id="content3"><div class="nestedDiv">Content Here</div></div>
<div id="content4"><div class="nestedDiv">Content Here</div></div>

I tried using examples I found here: How do you swap DIVs on mouseover? (jquery?) but it fails because of the nested divs.

Any ideas of how I can get this working in a way that all the content within a given div, including other divs, is shown on click? I'd also like to keep the first div in an active state when the page is first opened... change the active look of the li that is selected... but I haven't attempted to tackle that yet.

Any input is appreciated. Thanks!

Thanks!

1条回答
干净又极端
2楼-- · 2019-05-16 16:29

Add a class="content" on each content div

<style type="text/css">
.content
{
    display: none;
}
</style>

<script type="text/javascript">

$(document).ready(function() {

   $("#tab a").click(function() {

      //reset
      $(".content").hide();
      $("#tab .active").removeClass("active");

      //act
      $(this).addClass("active")
      var id = $(this).closest("li").attr("id").replace("tab","");
      $("#content" + id).show();
   });

});
</script>
查看更多
登录 后发表回答