使用Jquery在数组中显示以前的项目

时间:2017-02-02 10:44:08

标签: javascript jquery arrays

我有这个脚本,显示数组中的下16个项目。但是我希望它能够显示之前的16"返回"单击按钮。

这是我用于" Next"的脚本。按钮:



var YearList = $('.dateListItem li').toArray();

var index = 0;

displayNext();

$(".arrowRight").click(function() {
  // display next elements
  displayNext();
});

function displayNext() {
  $(YearList).hide();

  var list = $('.dateListItem');
  var index = list.data('index') % YearList.length || 0;

  list.data('index', index + 2);
  $(YearList.slice(index, index + 2)).show();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="arrowRight">NEXT</a>

<ul class="dateListItem">
  <li>1978</li>
  <li>1979</li>
  <li>1980</li>
  <li>1981</li>
  <li>1982</li>
  <li>1983</li>
</ul>
&#13;
&#13;
&#13;

所以现在我只需要采取其他方式。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

你可以用你的替换这个js代码,

var YearList = $('.dateListItem li').toArray();

var index = 0;

displayNext();

$(".arrowRight").click(function() {
  // display next elements
  displayNext();
});

$(".arrowLeft").click(function() {
  // display next elements
  displayPrev();
});

function displayNext() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var index = list.data('index') % YearList.length || 0;

  list.data('index', index + 16);             
  $(YearList.slice(index, index + 16)).show(); 
}

function displayPrev() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var index = list.data('index') % YearList.length || 0;
  index = index - 16;
  list.data('index', index);             
  $(YearList.slice(index - 16, index)).show(); 
}

在这里工作jsfiddle

答案 1 :(得分:0)

您可以通过稍微修改功能来实现之前的功能。 小提琴链接:jsfiddle

var YearList = $('.dateListItem li');

var index = 0;

displayNext();

$(".arrowLeft").click(function() {
  // display next elements
  displayPrevious();
});

$(".arrowRight").click(function() {
  // display next elements
  displayNext();
});

function displayNext() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var index = list.data('index') % YearList.length || 0;   

   list.data('index', index+2);  
  $(YearList.slice(index, index + 2)).show(); 
}

function displayPrevious() {
  $(YearList).hide();

  var list = $('.dateListItem'); 
  var pindex = list.data('pindex') % YearList.length || 0;   
  var YearListLength = YearList.length;
  list.data('pindex', pindex+2);  
  $(YearList.slice(YearListLength-2-pindex, YearListLength-pindex)).show(); 
}