通过点击分页数组javascript

时间:2016-05-15 12:29:02

标签: javascript jquery arrays jquery-pagination

我有两个链接:

<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);
}

});

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

我该怎么做?

最好的问候

1 个答案:

答案 0 :(得分:0)

问题是你要跟踪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 */ 
}
}