简体   繁体   English

Javascript:分页

[英]Javascript: Pagination

I have to get from and to indices of the records.我必须从和到记录的索引。

Ideas would be appreciated.想法将不胜感激。 For instance, if:例如,如果:

data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
records_per_page = 4

the page numbers would be 1,2,3,4,5 (last page having one record).页码为 1,2,3,4,5(最后一页有一条记录)。

I need to get the indices based on the page numbers.我需要根据页码获取索引。

For Example I click Page 1, it should give me 0 and 3 so that I send this from and to indices to server and then it returns me values [1,2,3,4]例如,我单击第 1 页,它应该给我 0 和 3,以便我将其从索引发送到服务器,然后返回值 [1,2,3,4]

If I click Page 2, it should give me 4 and 7 so that server returns me values [5,6,7,8]如果我单击第 2 页,它应该给我 4 和 7,以便服务器返回值 [5,6,7,8]

function(total, page_no){ 
 // Need to return the indices of the records
 return [from,to]
}

You could chunk the array down into only the first and last indices of every x amount of elements:您可以将数组分块为每 x 个元素的第一个和最后一个索引:

 var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] const size = 4 const getIndices = (d, p) => p && p <= Math.ceil(d.length / size) && d.reduce((a, o, i) => { const c = Math.floor(i / size); a[c] = [].concat((a[c] && a[c][0] || []), o); if(a[c].length === 1) a[c] = [a[c][0], a[c][0]] return a }, [])[p - 1].map(i => --i) for(var i = 1; i < Math.ceil(data.length / size) + 1; i++) { console.log(getIndices(data, i)) }

EDIT: I just realised this is a simple maths problem.编辑:我刚刚意识到这是一个简单的数学问题。 Use this code instead:请改用此代码:

 var length = 17 const size = 4 const getIndices = (p, s, l) => p && p <= Math.ceil(l / s) && [s * (p - 1), s * p > l - 1 ? l - 1 : s * p - 1] for(var i = 1; i < Math.ceil(length / size) + 1; i++) { console.log(getIndices(i, size, length)) }

Second edit:第二次编辑:

 var length = 17 const size = 4 const getIndices = (p, s, l) => +p && +p <= Math.ceil(l / s) && s * --p for(var i = 1; i < Math.ceil(length / size) + 1; i++) { console.log(getIndices(i, size, length)) }

Note, this function could be a lot shorter, but I have added 2 error checks: p checks to see if p actually exists.请注意,这个函数可能要短得多,但我添加了 2 个错误检查: p检查p是否确实存在。 && chains all of the conditions to make sure all of them are met. &&链接所有条件以确保满足所有条件。 p <= Math.ceil(d.length / size) checks whether p is bigger than the max amount of pages. p <= Math.ceil(d.length / size)检查p是否大于最大页数。 The next part is the actual logic, returning the page start (and end) indices.下一部分是实际逻辑,返回页面开始(和结束)索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM