使用选项卡导航到不同的html文件(HTML,JavaScript)

时间:2016-05-04 04:31:29

标签: javascript jquery html css

这是我第一次做这样的事情。

让我们说在我的HTML文件中我有类似

的内容
<div class="main_tabs">
    <ul class="tabs">
       <li id="home_tab"><a href="index.html">Home</a></li>
       <li id="other_tab"><a href="other.html">Other</a></li>
    </ul> 
</div>

然后在我的JavaScript文件中,我有类似

的内容
jQuery(document).ready(function() {
   jQuery('.main_tabs .tabs a').on('click', function(e)  {
       e.preventDefault();
       switch(this.id){
           case "home_tab":
           window.location.href = "index.html";
           break;
           case "other_tab":
           window.location.href = "other.html";
           break;
       }
   });
});

单击选项卡时,没有任何反应。我尝试了很多不同的东西,但我无法让它工作。任何人都可以帮助我(顺便说一下,我需要让preventDefault在函数中做一些其他的东西,所以我需要手动更改页面)?

2 个答案:

答案 0 :(得分:1)

您需要获取id或父li,因为a标记没有id属性。

jQuery(document).ready(function() {
  jQuery('.main_tabs .tabs a').on('click', function(e) {
    e.preventDefault();
    switch (this.parentNode.id) {
    // -----^-- get parent node and it's id
      case "home_tab":
        window.location.href = "index.html";
        break;
      case "other_tab":
        window.location.href = "other.html";
        break;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main_tabs">
  <ul class="tabs">
    <li id="home_tab"><a href="index.html">Home</a>
    </li>
    <li id="other_tab"><a href="other.html">Other</a>
    </li>
  </ul>
</div>

答案 1 :(得分:0)

您可以删除jquery,因为您已经在html中使用了锚点。 请参阅http://www.w3schools.com/html/html_links.asp