单击任何其他选项卡会产生问题

时间:2019-02-05 13:45:13

标签: jquery tabs

我正在尝试制作jquery选项卡,然后单击,我想在活动选项卡上使用叉形图标,但是如果我不关闭上一个选项卡,其他选项卡就会受到影响,请参见下面的代码,并请告诉我我在哪里做错了?

var text = '';
var tab = "";
var flag = 0;
var athis = '';

$(".tablinks").on("click", function() {
  var id = $(this).attr('rel');
  athis = $(this);
  $(this).addClass('active');

  if (flag == 0) {
    text = $(this).text();
    $(this).html('<i class="fas fa-times"></i>');
    $('.tabcontent').hide();
    $('#' + id).slideDown();
    flag = 1;
  } else {
    athis.html(text);
    $('#' + id).slideUp();
    flag = 0;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
  <button class="tablinks" rel="a">Are you interested</button>
  <button class="tablinks" rel="b">Call Us</button>
  <button class="tablinks" rel="c">Followus</button>
</div>

<div id="a" class="tabcontent">
  <h3>Are you interested</h3>
</div>

<div id="b" class="tabcontent">
  <h3>Contact us</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="c" class="tabcontent">
  <h3>Follow us</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

1 个答案:

答案 0 :(得分:0)

一个快速的解决方法是将这一行放在事件处理程序的顶部,但我认为可以重写您的代码以使其不必要:

 $('.tablinks:has(i)').not(this).click();

var text = '';
var tab = "";
var flag = 0;
var athis = '';

$(".tablinks").on("click", function() {
  $('.tablinks:has(i)').not(this).click();
  var id = $(this).attr('rel');
  athis = $(this);
  $(this).addClass('active');

  if (flag == 0) {
    text = $(this).text();
    $(this).html('<i class="fas fa-times"></i>');
    $('.tabcontent').hide();
    $('#' + id).slideDown();
    flag = 1;
  } else {
    athis.html(text);
    $('#' + id).slideUp();
    flag = 0;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
  <button class="tablinks" rel="a">Are you interested</button>
  <button class="tablinks" rel="b">Call Us</button>
  <button class="tablinks" rel="c">Followus</button>
</div>

<div id="a" class="tabcontent">
  <h3>Are you interested</h3>
</div>

<div id="b" class="tabcontent">
  <h3>Contact us</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="c" class="tabcontent">
  <h3>Follow us</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>