javascript - 如何创建 jquery 上一个和下一个按钮来遍历数组中的 URL(分页)

标签 javascript jquery pagination

我有一个 URL 数组,比如

pageList = ["index.html", "01.html", "02.html"]

并且我想创建一个函数,其中 .prev 和 .next 转到该数组中的上一个/下一个项目,因此如果我在 index.html 中,单击“下一步”将转到“01.html”,并且如果我在“01.html”,它将转到“02.html”,依此类推。

我怎样才能做到这一点?我发现了很多“分页”jquery 插件,但它们似乎都通过同一 URL 中的 div 进行分页,但我需要一些实际上转到另一个页面的东西,例如

window.location = currentLocation + 1

抱歉这个菜鸟问题,它确实来自菜鸟。 塔!

最佳答案

你可以这样做:

var pageList = ["index.html", "01.html", "02.html"];
var url = window.location.pathname; // e.g. http://me.com/index.html
var page = url.substring(url.lastIndexOf('/')+1); // e.g. index.html
var currentPosition = pageList.indexOf(page); // e.g. 0, 1 or 2

document.getElementById('next-btn').onclick = function(){
    // if the URL is not in the list, do nothing
    if(currentPosition==-1) return;
    // if we're at the end, go back to index, else, go to next page
    window.location = currentPosition<pageList.length-1? pageList[++currentPosition]:pageList[0];
}

在每个页面上插入该脚本,如果您有一个 ID 为 next-btn 的元素可供点击,它应该可以工作。

如果你不熟悉最后一行的语法,也可以这样写:

if(currentPosition<pageList.length-1) {window.location = pageList[++currentPosition];}
else {window.location = pageList[0];}

关于javascript - 如何创建 jquery 上一个和下一个按钮来遍历数组中的 URL(分页),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26076042/

相关文章:

python - 大数据集的 Django 分页太慢

javascript - JS : Why when I click the button nothing happens?

javascript - ReactJs:如何转义 <p> 包含来自 props 的数据渲染

javascript - 如何将表单名称传递给 JavaScript 并使用它来读取表单值

javascript - 如何将 CSS 类添加到此脚本函数

jQuery 计数器在滚动时开始递增,但不会在最大值处停止

php - 在 CakePHP 2.x 分页中按计算的 MySQL 字段排序

jquery - 数据表分页字符 "<<"和 "<"在 IE 和 Safari 中无法正确显示

javascript - 通过按钮显示更多和更少

php - 拉拉维尔 : How to specify the number of items in pagination via route variable