You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现网页序列导航按钮(上一页/下一页)的JavaScript问题

实现网页序列的上一页/下一页导航按钮功能

我需要编写JavaScript代码,实现网页序列的上一页/下一页导航按钮功能,页面URL列表和按钮在同一个HTML文件里。比如当前在test_pg5.htm页面时,点「Previous」要跳转到test_pg4.htm,点「Next」要跳转到test_coursecomplete.htm。

现有HTML代码

<ul class="menu">
    <li data-mc-id="0"><a href="../../courses/test/comms_view_intro.htm">Main Course Page</a>
        <ul class="sub-menu">
            <li data-mc-id="1"><a href="../../courses/test/test_pg1.htm">Topic 1</a></li>
            <li data-mc-id="2"><a href="../../courses/test/test_pg2.htm">Topic 2</a></li>
            <li data-mc-id="3"><a href="../../courses/test/test_pg3.htm">Quiz 1</a></li>
            <li data-mc-id="4"><a href="../../courses/test/test_pg4.htm">Topic 3</a></li>
            <li data-mc-id="5"><a href="../../courses/test/test_pg5.htm" class="selected" aria-current="true">Quiz 2</a></li>
            <li data-mc-id="6"><a href="../../courses/test/test_coursecomplete.htm">Course Completion Page</a></li>
        </ul>
    </li>
</ul>

<button class="prevLink">Previous</button>
<button class="nextLink">Next</button>

原脚本(无法正常运行)

$(document).ready(function() {
    var links = Array.prototype.slice.call(document.querySelectorAll('.menu a'));
    var index = links.indexOf(currentFocus);

    $('.nextLink').click(function() {
        window.location.href = links[index + 1];
    });

    $('.prevLink').click(function() {
        window.location.href = links[index - 1];
    });
});

问题分析与修复方案

原脚本有两个核心问题:

  1. currentFocus未定义,无法定位当前页面对应的链接
  2. links[index+1]是DOM元素,不是URL地址,直接赋值给window.location.href无效

另外还需要处理边界情况:第一页时禁用「Previous」按钮,最后一页时禁用「Next」按钮,避免无效跳转。

修复后的脚本:

$(document).ready(function() {
    // 获取子菜单中所有属于页面序列的链接
    const links = Array.from(document.querySelectorAll('.sub-menu a'));
    // 定位当前页面对应的选中链接
    const currentLink = document.querySelector('.sub-menu a.selected');
    if (!currentLink) return; // 未找到当前链接时直接退出

    const currentIndex = links.indexOf(currentLink);

    // 绑定上一页按钮事件
    $('.prevLink')
        .click(function() {
            if (currentIndex > 0) {
                window.location.href = links[currentIndex - 1].href;
            }
        })
        .prop('disabled', currentIndex === 0); // 第一页时禁用按钮

    // 绑定下一页按钮事件
    $('.nextLink')
        .click(function() {
            if (currentIndex < links.length - 1) {
                window.location.href = links[currentIndex + 1].href;
            }
        })
        .prop('disabled', currentIndex === links.length - 1); // 最后一页时禁用按钮
});

关键修复点

  • 用.sub-menu a.selected定位当前页面的链接,替代未定义的currentFocus
  • 从DOM元素中提取href属性作为跳转目标,而非直接使用DOM元素
  • 添加索引边界判断,防止越界错误,同时给首尾页的对应按钮添加禁用状态
  • 用Array.from替代Array.prototype.slice.call,更简洁地将NodeList转为数组

内容的提问来源于stack exchange,提问作者lc2301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:16:03