通过单击分页数组 javascript

paginating arrays javascript by click

我有两个 links:

<a href="#" id="theone" data-do="1" class="loopit">loop it</a>
<a href="#" id="thetwo"  data-do="2" class="loopit">loop it 2</a>

然后点击我触发一​​个循环数组的函数。当有一个循环时它工作得很好但是当有更多循环时它会搞砸,在这个例子中是两个。:

var jsonArray = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];
var jsonArray2 = ["january","fabruar","march","april","may","june","july","august","september","october","november","december"];
var current_group = 0;
var group_size= 5;
var group_size2= 2;
var theskip;
function cycleArray(thearr,thesize) {
var current_items = thearr.slice(current_group, current_group + thesize);
var skip = current_group += thesize;

console.log(current_items);
console.log(skip);

if(current_group > thearr.length) { 
    console.log("no more");
/* then we stop! no more items, so maybe disable button etc */ 
}
}

$(".loopit").on("click", function(e){
e.preventDefault();
var theclicked = $(this).attr("data-do");

//alert(theclicked);
if (theclicked == "1") {
    cycleArray(jsonArray,group_size);
}else{
    cycleArray(jsonArray2,group_size2);
}

});

所以问题是跳过的部分。它保存了最后一个,这是至关重要的,但是如果我按下第一个 link 我确实得到了前 5 个,但是如果我按下第二个 link,我从正确的数组中得到两个结果(很好)但显然它是从第五个开始的,而不是开始。

我该怎么做?

此致

问题是您正在使用两个数组的相同变量跟踪 current_group。因此,当您单击第一个大小为 5 的按钮时,current_group var 将设置为 5,因此下一次对 arrayJson2 的 cycleArray 调用从位置 5 开始。

在 JavaScript 中,您可以将数组视为对象并分配它们的属性,因此更好的解决方案是像这样跟踪 current_group

var jsonArray = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];
var jsonArray2 = ["january","fabruar","march","april","may","june","july","august","september","october","november","december"];

// Here initialize them with zero
jsonArray2.current_group = 0;
jsonArray.current_group = 0;

var current_group = 0;
var group_size= 5;
var group_size2= 2;
var theskip;
function cycleArray(thearr,thesize) {
// now you can sefely access the property coresponding the correct array
var current_items = thearr.slice(thearr.current_group, thearr.current_group + thesize);
var skip = thearr.current_group += thesize;

console.log(current_items);
console.log(skip);

if(thearr.current_group > thearr.length) { 
    console.log("no more");
/* then we stop! no more items, so maybe disable button etc */ 
}
}