4

我知道显示/隐藏的东西已经被堆栈覆盖到死,但我找不到适合我的解决方案,抱歉。我已经尝试了几种我发现的 JS/jQuery 解决方案,但不能完全按照我想要的方式行事。

我有许多内容非常相似的 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 或链接的命名结构。

4

3 回答 3

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

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

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

    });
});

把它包在一个$(document).ready或任何地方,你应该很高兴去我的朋友。学好代码,以后你就是gosu。

于 2012-12-14T19:46:13.277 回答
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();
   });
});
于 2012-12-14T20:02:33.850 回答
0

我建议您将on()jquery 函数与选择器一起使用。您还可以div使用 css 显示默认值。是完整的代码。

于 2012-12-15T23:18:16.160 回答