隐藏几个div,一个默认显示,并根据链接点击来切换(显示/隐藏)它们?

4
我知道在 Stack 上已经有关于显示/隐藏的解释,但是我找不到适合我的解决方法,很抱歉。我尝试了几个我找到的 JS/jQuery 解决方案,但无法完全按照自己想要的方式工作。
我有许多内容非常相似的 div(根据所选版本略有不同),并且所有 div 都具有完全相同的样式。
期望行为
默认情况下,我希望一个 div 显示,而其他所有 div 都隐藏。然后,根据链接点击,显示不同版本的 div 并隐藏所有其他内容的 div。
基本 HTML
<div class="container">
  <h1>Header</h1>
  <p>Basic info about page</p>
  <ul>
    <li><a href="#ver1" id="linkToVer1">Version 1</a></li>
    <li><a href="#ver2" id="linkToVer2">Version 2</a></li>
    // More links to other divs
  </ul>

  <div class="content" id="ver1">    // I'd like this div to be the default
     Content here                    // when the page loads. All other divs 
  </div>                             // are hidden until a link is clicked.

  <div class="content" id="ver2">
     Content here
  </div>

  // More content divs
</div>

我将拥有多达十二个不同版本的这些内容div。
JS或jQuery都可以,但更喜欢使用jQuery,因为我可能会添加某种显示/隐藏效果。我并不太关心div或链接的命名结构。
3个回答

3
$("div.containter ul li").each(function(){
    $(this).onclick(function(){

       $("div.content").hide();

      $("div" + $(this).attr("href")).show();

    });
});

将其包装在$(document).ready或其他地方,你就可以放心去做了,朋友。学好这段代码,这样在未来,你就是一个高手。


@AtifMohammedAmeenuddin 哈哈,是啊,那样会更好。我有一瞬间有点疯狂了。 - thatidiotguy
我想你是指这个:$("div#" + $(this).attr("href")).show();?编辑:没事,我没有仔细阅读帖子开头。 - Bram Vanroy
@BramVanroy 没有,那会导致“div##1”。 - thatidiotguy
@BramVanroy 没问题。谢谢您检查我的语法。 - thatidiotguy

0

我建议您使用带有选择器的 on() jQuery 函数。您还可以使用 CSS 显示默认的 div这里是完整的代码。


0

加入更多RESTful的行为怎么样?

$(function(){
   // get the location hash
   var hash = window.location.hash;
   // hide all
   $('div.content').hide();
   if(hash){
      // show the div if hash exist
      $(hash).show();
   }else{
      // show default 
      $("#ver1").show();
   }
   $("div.containter ul li a").click(function(){
      // hide all
      $('div.content').hide();
      $($(this).attr("href")).show();
   });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接