我有一个 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/