如何使用左右按钮循环div?

时间:2016-11-13 15:57:59

标签: jquery

我尝试使用左右按钮循环显示6个div,我们的想法是您可以左右移动,所选的div将使该类具有“活动”功能。然后当你向左或向右单击时,它将移动到下一个div并从前一个div中删除该类,并将其添加到沿着该行的下一个。

这是我的Js

 $(function () { // this is a shortcut for document ready
    var stuff = ['box1', 'box2', 'box3', 'box4', 'box5','box6'],
        counter = 0;

    console.log(stuff[counter]); // your initial value


    $('.right').click(function () {
        counter = (counter + 1) % stuff.length;
        valueNw = stuff[counter];
        console.log(valueNw); 
    });
    $('.left').click(function () {
        counter = (counter - 1) % 1;
        console.log(stuff[counter]); 
    });


});

codePen

任何想法都会受到赞赏,我已经让它前进而不是倒退,如果有更好的方法,请告诉我。

2 个答案:

答案 0 :(得分:1)

在您的代码(counter - 1) % 1中始终会生成0,因此始终指向0。相反,在stuff.lengthcounter的情况下,通过将值替换为0来更改后向条件以避免负值。

$(function() { // this is a shortcut for document ready
  var stuff = ['box1', 'box2', 'box3', 'box4', 'box5', 'box6'],
    counter = 0;

  console.log(stuff[counter]); // your initial value


  $('.right').click(function() {
    counter = (counter + 1) % stuff.length;
    valueNw = stuff[counter];
    console.log(valueNw);
  });
  $('.left').click(function() {
    // replace with stuff.length if counter holds 0 and decrement
    counter = (counter || stuff.length) - 1;
    console.log(stuff[counter]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="right">right</button>
<button class="left">left</button>

答案 1 :(得分:1)

这个答案是对@ Pranav答案中的问题的回答。这就是我根据右/左键单击选择div的方法。

var eleName = ".box1";
var eleCount = 0;
var currIndex = 1;

$(function () { // this is a shortcut for document ready
     eleCount = $('.box').length;
     $(eleName).toggleClass('active');
     ShowConsoleInfo();

  $('.right').click(function () {
        if(currIndex <= eleCount - 1){
          //Toggle current box.
          $(eleName).toggleClass('active');
          //Build the name by incrementing current index.
          currIndex++;
          eleName = '.box' + currIndex;
          //Toggle newly selected box.
          $(eleName).toggleClass('active');
          ShowConsoleInfo();
        }
    });

    $('.left').click(function () {
        if(currIndex >= 2){
          //Toggle current box.
          $(eleName).toggleClass('active');
          //Build the name by decrementing current index.
          currIndex--;
          eleName = '.box' + currIndex;
          //Toggle newly selected box.
          $(eleName).toggleClass('active');
          ShowConsoleInfo();
        }
    });
});

function ShowConsoleInfo(){
    console.clear();
    console.log("Current Index: " + currIndex);
    console.log("Element Count: " + eleCount);
    console.log("Current Box name: " + eleName);
};
Right Left Div Selection Example [jQuery]上查看Addam Boord的笔@BOORDACodePen)。