根据箭头更改多个div

时间:2017-01-31 14:51:44

标签: javascript jquery html css

我已经为用户创建了一个输入部分来编写自己的工作。我有多个div,我想从可以点击的左右箭头改变div。

$(document).ready(function() {
  $('.menubody:nth-child(1)').show('slow');
  $('.menubody:nth-child(1)').hide('slow');
  $('.fa-caret-right').on({
    click: function() {
      var i = $('.menubody:visible').index();
      var len = $('.menubody').length;
      var next;
      if (i >= 0) {
        if (i == len - 1) {
          next = $('.menubody:eq(0)');
        } else {
          next = $('.menubody:eq(' + (i + 1) + ')');
        }
        $('.menubody:visible').hide();
        $(next).show();
      }
    }
  });
});

编辑:

我有一个工作示例(请参阅fiddle),在按下“正确”时更改和更改内容。

如何制作,以便'left'div将内容移至上一个?并添加多个内容区域进行更改?

有关用法的示例布局(不是jQuery工作),请see here

2 个答案:

答案 0 :(得分:1)

我认为你应该在这里使用nth-child()jQuery选择器。只需在每次单击按钮右侧时增加n的值,并在每次单击左箭头时减小n的值。

$('#left-arrow').on('click', function(){
  var i++; 
  $('main-div:nth-child(i-1)').hide();
  $('main-div:nth-child(i)').show();
})   

以下是阅读详情的链接:W3 Schools :nth-child() selector

答案 1 :(得分:1)

使用jQuery' .prev().next()。如果他们返回零长度的集合,请使用.last().first()来循环浏览您的内容(不确定是否需要此内容)。



$(function() {
  $('.tabs-container div').not(':first-child').hide();

  $('#tabs li a').click(function() {
    var $clickedLink = $(this),
        $visible = $('.tabs-container div:visible');

    $visible.each(function(){
      var $this = $(this),
          $parentContainer = $this.parents('.tabs-container').eq(0),
          $toShow;
      
      if( $clickedLink.is('.prev') ){
         $toShow = $this.prev('div').length ? $this.prev('div') : $('div', $parentContainer).last();
      } else {
         $toShow = $this.next('div').length ? $this.next('div') : $('div', $parentContainer).first();
      }
                        
      $this.hide();
      $toShow.show();
    });

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="tabs">
  <li><a href="#" class="prev">Left Arrrow</a>
  </li>
  <li><a href="#" class="next">Right Arrow</a>
  </li>
</ul>
<div class="tabs-container">
  <div id="content1">Content for link 1. Should display only when Link 1 is clicked.</div>
  <div id="content2">Content for link 2. Should display only when Link 2 is clicked.</div>
  <div id="content3">Content for link 3. Should display only when Link 3 is clicked.</div>
  <div id="content4">Content for link 4. Should display only when Link 4 is clicked.</div>
</div>

<p>Unrelated text is here. Text in this area is static and should display at all times.</p>

<div class="tabs-container">
  <div id="content1-2">Additional content for link 1. Should display only when Link 1 is clicked.</div>
  <div id="content2-2">Additional content for link 2. Should display only when Link 2 is clicked.</div>
</div>

<p>More unrelated text</p>

<div class="tabs-container">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div>
&#13;
&#13;
&#13;