多个JQuery选项卡有问题

时间:2015-03-22 03:57:18

标签: jquery jquery-tabs

我是JQuery的业余爱好者,我试图在一个页面上使用多个JQuery选项卡容器,但不希望它们相互影响。你会从我的例子中看到我的意思。我知道我在JS中遗漏了一些东西,但无法弄明白。我已经尝试在JS中添加各种父代和兄弟代码,但我无法获得任何使容器独一无二的东西。任何帮助将非常感激!

$('ul.tabs li').click(function(){
                var tab_id = $(this).attr('link-tab');

                $('ul.tabs li').removeClass('current');
                $('.tab-content').removeClass('current');

                $(this).addClass('current');
                $("#"+tab_id).addClass('current');
            })

这里是link on CODEPEN

1 个答案:

答案 0 :(得分:2)

link-tab attr更改为data-tab attr

<li class="tab-link current" link-tab="tab-3">08:30-09:30</li><li class="tab-link current" data-tab="tab-3">08:30-09:30</li>

 $(document).ready(function() {
   $('.tab-link').click(function() {
     //find closest div
     div_container = $(this).closest('.container');
     //remove current class from all .tab-link and .tab-content class under closest div container
     div_container.find('.tab-link').removeClass('current');
     div_container.find('.tab-content').removeClass('current');

     //add current class to current click tab and corresponding div
     $(this).addClass('current');
     tab_id = $(this).attr('data-tab');
     $('#' + tab_id).addClass('current');

   });
 });
.container {
  width: 95%;
  margin-top: 30px;
  padding: 8px;
  -webkit-box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.4);
  -moz-box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.4);
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.4)
}
ul.tabs {
  margin: 0px;
  padding: 0px;
  list-style: none;
}
ul.tabs li {
  background: #009a97;
  color: white;
  display: inline-block;
  margin-bottom: 8px;
  padding: 8px;
  cursor: pointer;
  font-weight: bold;
}
ul.tabs li.current {
  background: none;
  color: #222;
  border: none;
}
.tab-content {
  display: none;
  padding-left: 8px;
  padding-top: 10px;
  border-top: 1px solid #009a97
}
.tab-content.current {
  display: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <ul class="tabs">
    <li class="tab-link current" data-tab="tab-1">08:30-09:30</li>
    <li class="tab-link" data-tab="tab-2">Evaluation</li>
  </ul>
  <div id="tab-1" class="tab-content current">
    <div class="togg">
      <p><strong>Presentation</strong>
      </p>

      <p><em>Presenter</em>
        <br>
      </p>
    </div>
  </div>
  <div id="tab-2" class="tab-content">Embedded evaluation</div>
</div>
<div class="container">
  <ul class="tabs">
    <li class="tab-link current" data-tab="tab-3">08:30-09:30</li>
    <li class="tab-link" data-tab="tab-4">Evaluation</li>
  </ul>
  <div id="tab-3" class="tab-content current">
    <div class="togg">
      <p><strong>Presentation2</strong>
      </p>

      <p><em>Presenter</em>
        <br>
      </p>
    </div>
  </div>
  <div id="tab-4" class="tab-content">Embedded evaluation</div>
</div>