javascript打开隐藏的div太大了

时间:2015-01-14 23:08:36

标签: javascript

我有这个代码它工作正常问题是我需要使用它60个链接 这将产生大约3600行java脚本代码,以便能够看到60个div的隐藏内容

抱歉,已经很晚了,所以发错了代码,它没有用,

忘了提及我的脚本是带有两个链接的菜单,当页面加载链接时显示而不是显示链接,而是显示欢迎消息,当点击它时显示其内容,当点击帮助时它取代了与之相抗衡

确定我的示例现在运行正常。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#welcome-content").show();   
    $("#help-content").hide();
    $("#about-content").hide();


    $("#about-anchor").click(function(){
    $("#welcome-content").hide();   
    $("#help-content").hide();
    $("#about-content").show();
    });

    $("#help-anchor").click(function(){
    $("#welcome-content").hide();  
    $("#help-content").show();
    $("#about-content").hide();
    });
    });
</script>

    <div id="anchor-div">
      <a id="about-anchor" href="javascript:;">
       About
      </a>     
    </br>

    <a id="help-anchor" href="javascript:;">
      Help
    </a>   
    </br>    
    </div>

<div id="content-div">
  <div id="welcome-content">welcome to help system</div>    
  <div id="about-content">About=123</div>
  <div id="help-content">Help=456</div>
</div>

jsfiddle demo here

1 个答案:

答案 0 :(得分:0)

利用每个li的索引来显示/隐藏相应的div:

$('#anchor-div a').click(function(e) {
  e.preventDefault(); // Dont follow the Link
  $('#content-div>div').hide(); // Hide all divs with content

  var index = $(this).index('a'); // Get the position of the a relative to other a
  $('#content-div>div').eq(index + 1).show(); // Show the div on the same position as the li-element
});

&#13;
&#13;
$('#anchor-div a').click(function(e) {
  e.preventDefault(); // Dont follow the Link
  $('#content-div>div').hide(); // Hide all divs with content

  var index = $(this).index('a'); // Get the position of the a relative to other a
  $('#content-div>div').eq(index + 1).show(); // Show the div on the same position as the li-element (skip welcome div)
});
&#13;
#content-div>div {
  display: none;
  /* Hide all divs */
}
#content-div>div:first-child {
  display: block;
  /* Show welcome */
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anchor-div">
  <a href="#"> About</a><br />
  <a href="#"> Help </a>
</div>


<div id="content-div">
  <div>Welcome!</div>
  <div>About</div>
  <div>Help</div>
</div>
&#13;
&#13;
&#13;

这样你既不需要id也不需要类

// 编辑:我更改了答案以匹配新问题。我使用css隐藏div(不像js的纪念中提到的那样)