javascript - 如何在没有 PHP(仅 jQuery/javascript)的情况下按顺序链接到下一页和上一页

标签 javascript jquery html hyperlink next

假设我有一系列页面(“example_1.html”、“example_2.html”、“example_3.html”等),我希望每个页面都有下一个/上一个按钮。我不想要任何过于花哨的分页,只需要上一个和下一个按钮。

我还希望这些页面在到达末尾时循环返回,这样“example_12.html”自然会循环回到开头的“example_1.html”。

我希望能够通过创建另一个页面来简单地将页面添加到序列中,而不必返回到现有页面来更改链接。

有没有不用 php 或服务器端数据获取的简单方法?此外,我不想随着时间的推移添加更多页面而不断更新列表,并且我不想在页面中包含任何列表

我总能找到接近的东西,但从来没有我理解的东西,对于不是最精通 javascript 的人来说,是否有真正简化的版本?

最佳答案

如果您真的不会使用服务器端语言(也许如果您希望静态托管它),并且不想手动设置链接的麻烦,我建议您使用静态站点生成器喜欢Jekyll .如果你确定你想要一个 JS 解决方案,这应该可行:

// Get current page url, remove the `.html` extension and split by underscore.
// The current page number will be the last element in the returned array.
var urlFrags = window.location.href.replace(".html", "").split("_"),
    // Get the last element of the `urlFrags` array and parse. This should be the current page number.
    curPage = parseInt(urlFrags[urlFrags.length - 1]),
    // Form the url of the expected next page. (Current page number + 1.)
    nextPage = "example_" + (curPage + 1) + ".html";

// Check if a page on this domain exists.
// Success returns true, error returns false.
function pageExists(url, callback){
    $.ajax({
        url: url,
        type: "HEAD",
        success: function(){ callback(true); },
        error: function(){ callback(false); }
    });
}

// Setup links for later.
var backLink, nextLink;

// Check if expected next page exists.
pageExists(nextPage, function(exists){
    if(exists){
        // If it does, set nextlink as expected next page.
        nextLink = nextPage;
    } else {
        // Otherwise, loop back to the start.
        nextLink = "example_1.html";
    }
});

if(curPage > 1){
    // We know the previous page must exist, so long as you're not on the first page.
    backLink = "example_" + (curPage - 1) + ".html";

    // It's not practical to try and loop back to the end if you go back on the first page.
    // You'd have to query pages until you got an error. So just leave it undefined, and ideally remove the button.
}

// Example button settings, using jQuery. Replace with whatever you're using.
$("#back").prop("href", backLink);
$("#next").prop("href", nextLink);

如果不设置相同的站点,显然无法测试所有这些,所以请原谅任何错误;)

关于javascript - 如何在没有 PHP(仅 jQuery/javascript)的情况下按顺序链接到下一页和上一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25614860/

相关文章:

java - 如何构建 HTML org.w3c.dom.Document?

javascript - HTML 5 需要验证 .NET Web 表单下拉列表和日期时间选择器

javascript - 将玩家移向鼠标方向?

javascript - 如何将两个文本框合并成一行

javascript - Codeigniter 中自动完成多个值

javascript - 如何使用 Select2 4.0 使下拉菜单向左打开

php - 表单提交导致多个请求加载同一页面

javascript - 如何更改 Vue.js 中某个 div 的颜色

javascript - 如何在axios post请求发送的php中检索变量

javascript - JavaScript 和 Node.js 中多个请求之间的局部变量