使用 jquery 更改具有嵌套内容的 div 的可见性,onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2290866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:11:32  来源:igfitidea点击:

using jquery to change visibility of divs with nested content, onclick

jqueryhtmlonclickvisibility

提问by Peachy

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 的可见性。我的 html 如下所示:

<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.

我尝试使用我在这里找到的示例:How do you swap DIVs on mouseover? (jquery?)但由于嵌套的 div 而失败。

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.

关于如何使给定 div 中的所有内容(包括其他 div)在单击时显示的任何想法?我还想在第一次打开页面时将第一个 div 保持在活动状态...更改所选 li 的活动外观...但我还没有尝试解决这个问题。

Any input is appreciated. Thanks!

任何输入表示赞赏。谢谢!

Thanks!

谢谢!

回答by Francisco Aquino

Add a class="content" on each content div

在每个内容 div 上添加一个 class="content"

<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>