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

如何用JavaScript自动填充导航链接,无需硬编码识别文件?

问题描述

我目前处于BED学习初期阶段,希望获得偏代码实现而非精简高效的方案,这样能更好地学习。

我正在做一个展示学习技能成长过程的网站,所有页面都需要导航栏,但重复输入相关链接太费时间。

之前谷歌搜过这个问题,结果大多说“不行!”,偶尔看到有人用file函数,但我在jQuery或JavaScript里找不到这个函数。

所以我的问题是:有没有办法让JavaScript无需硬编码就能识别某个位置的文件?

我的文件夹结构

/school: 
./index.html
./css
./js
./programingFoundation:
  ./pfdindex.html
  ./module1
  ./module2
  ./...
./frontEndTech:
  ./fetIndex.html
  ./module1
  ./module2
  ./...

我尝试编写的导航代码(mainNav.js)

function innsertMainNav() {
    const mainNavTitles = [
        { button: 'Home', url: '/index.html', active: true },
        { button: 'JS Basic', url: '/programmingFoundations/pfindex.html', active: true },
        { button: 'Frontend', url: '/forntEndTechnologies/fetindex.html', active: true },
        { button: 'OOP', url: './programmingWithObjects/pwoindex.html', active: true },
        { button: 'Project Methodology', url: '/projectMethodology/pmindex.html', active: false },
        { button: 'Semester Project', url: '/semesterProject/smindex.html', active: false },
        { button: 'JS Servers', url: '/javaScriptServers/jssindex.html', active: false },
        { button: 'dataBases', url: '/databases/dbindex.html', active: false },
        { button: 'Rest Api', url: '/restApi/raindex.html', active: false },
        { button: 'Servers', url: '/serverDeployment/sdindex.html', active: false },
        { button: 'Exam', url: '/examProject/epindex.html', active: false }
    ];

    //insert header
    $('head').after('<header class="container-md bg-light"></header>');
    // add title and logo line
    $('header').append(`<div class="row"><h1>${document.title}</h1></div>`);
    
    // add Navigation 
    $('header').append('<nav id="mainNav" class="row">\
    <div id="outerDiv" class="container-fluid">\
        <button\
            class="navbar-toggler" type="button" data-bs-toggle="collapse"\
            data-bs-target="#collapsing" aria-controls="collapsing"\
            aria-expanded="false" aria-label="Togglenavigation">\
            <span class="navbar-toggler-icon"></span>\
        </button>\
    <div id="collapsing" class="collapse navbar-collapse">\
        <ul id="mainNavList" class="navbar-nav me-auto mb-2 mb-lg-0"></ul>\
    </div></div></nav>');

    // Populate main NAV
    for (let i = 0; i < 10; i++) {
        if (mainNavTitles[i].active) {
            $('ul#mainNavList').append(`<li>\
            <a class="col" href="..${mainNavTitles[i].url}">\
            ${mainNavTitles[i].button}\
            </a></li>`);
        }
        else {
            break;
        }
    }

    $('#mainNav').addClass('navbar navbar-expand-lg navbar-light');
    $('nav a').addClass('nav-link');
}

解决方案

首先明确:浏览器环境下的JavaScript出于安全限制,无法直接读取本地文件夹的文件列表,你看到的file函数是Node.js环境的API,浏览器端用不了。

下面给你两个偏基础代码实现的方案,都能避免在每个页面重复写导航代码:

方案1:抽离导航配置文件(最适合初学者)

把导航数据单独放在一个JS文件里,所有页面共用,修改导航只需要改这一个文件。

步骤1:创建导航配置文件(/js/navConfig.js)

// 全局挂载导航配置,所有页面都能读取
window.navConfig = [
    { button: '首页', url: '/index.html', active: true },
    { button: 'JS基础', url: '/programmingFoundations/pfindex.html', active: true },
    { button: '前端技术', url: '/frontEndTechnologies/fetindex.html', active: true },
    { button: '面向对象', url: '/programmingWithObjects/pwoindex.html', active: true },
    { button: '项目方法论', url: '/projectMethodology/pmindex.html', active: false },
    { button: '学期项目', url: '/semesterProject/smindex.html', active: false },
    { button: 'JS服务端', url: '/javaScriptServers/jssindex.html', active: false },
    { button: '数据库', url: '/databases/dbindex.html', active: false },
    { button: 'Rest Api', url: '/restApi/raindex.html', active: false },
    { button: '服务器部署', url: '/serverDeployment/sdindex.html', active: false },
    { button: '考试项目', url: '/examProject/epindex.html', active: false }
];

步骤2:修改mainNav.js

修正拼写错误、路径问题,改用全局配置数据:

function insertMainNav() {
    // 从全局配置读取导航数据
    const mainNavTitles = window.navConfig;

    // 插入header
    $('head').after('<header class="container-md bg-light"></header>');
    // 添加标题行
    $('header').append(`<div class="row"><h1>${document.title}</h1></div>`);
    
    // 添加导航结构
    $('header').append('<nav id="mainNav" class="row">\
    <div id="outerDiv" class="container-fluid">\
        <button\
            class="navbar-toggler" type="button" data-bs-toggle="collapse"\
            data-bs-target="#collapsing" aria-controls="collapsing"\
            aria-expanded="false" aria-label="切换导航">\
            <span class="navbar-toggler-icon"></span>\
        </button>\
    <div id="collapsing" class="collapse navbar-collapse">\
        <ul id="mainNavList" class="navbar-nav me-auto mb-2 mb-lg-0"></ul>\
    </div></div></nav>');

    // 填充导航列表
    for (let i = 0; i < mainNavTitles.length; i++) {
        if (mainNavTitles[i].active) {
            // 自动处理路径:根路径开头的url不用加../,避免错误
            const href = mainNavTitles[i].url.startsWith('/') 
                ? mainNavTitles[i].url 
                : `../${mainNavTitles[i].url}`;
            $('ul#mainNavList').append(`<li class="nav-item">\
            <a class="nav-link" href="${href}">\
            ${mainNavTitles[i].button}\
            </a></li>`);
        } else {
            break;
        }
    }

    $('#mainNav').addClass('navbar navbar-expand-lg navbar-light');
}

步骤3:页面引入文件

在所有需要导航的HTML页面的</body>前添加:

<script src="/js/navConfig.js"></script>
<script src="/js/mainNav.js"></script>
<script>
    // 调用函数渲染导航
    insertMainNav();
</script>

方案2:AJAX加载JSON配置文件(进阶学习异步加载)

把导航数据放在JSON文件里,用jQuery的AJAX加载,适合学习异步请求知识。

步骤1:创建JSON配置文件(/js/navConfig.json)

[
    { "button": "首页", "url": "/index.html", "active": true },
    { "button": "JS基础", "url": "/programmingFoundations/pfindex.html", "active": true },
    { "button": "前端技术", "url": "/frontEndTechnologies/fetindex.html", "active": true },
    { "button": "面向对象", "url": "/programmingWithObjects/pwoindex.html", "active": true },
    { "button": "项目方法论", "url": "/projectMethodology/pmindex.html", "active": false },
    { "button": "学期项目", "url": "/semesterProject/smindex.html", "active": false },
    { "button": "JS服务端", "url": "/javaScriptServers/jssindex.html", "active": false },
    { "button": "数据库", "url": "/databases/dbindex.html", "active": false },
    { "button": "Rest Api", "url": "/restApi/raindex.html", "active": false },
    { "button": "服务器部署", "url": "/serverDeployment/sdindex.html", "active": false },
    { "button": "考试项目", "url": "/examProject/epindex.html", "active": false }
]

步骤2:修改mainNav.js

function insertMainNav() {
    // 用jQuery AJAX加载JSON配置
    $.getJSON('/js/navConfig.json', function(mainNavTitles) {
        // 插入header
        $('head').after('<header class="container-md bg-light"></header>');
        // 添加标题行
        $('header').append(`<div class="row"><h1>${document.title}</h1></div>`);
        
        // 添加导航结构
        $('header').append('<nav id="mainNav" class="row">\
        <div id="outerDiv" class="container-fluid">\
            <button\
                class="navbar-toggler" type="button" data-bs-toggle="collapse"\
                data-bs-target="#collapsing" aria-controls="collapsing"\
                aria-expanded="false" aria-label="切换导航">\
                <span class="navbar-toggler-icon"></span>\
            </button>\
        <div id="collapsing" class="collapse navbar-collapse">\
            <ul id="mainNavList" class="navbar-nav me-auto mb-2 mb-lg-0"></ul>\
        </div></div></nav>');

        // 填充导航列表
        for (let i = 0; i < mainNavTitles.length; i++) {
            if (mainNavTitles[i].active) {
                const href = mainNavTitles[i].url.startsWith('/') 
                    ? mainNavTitles[i].url 
                    : `../${mainNavTitles[i].url}`;
                $('ul#mainNavList').append(`<li class="nav-item">\
                <a class="nav-link" href="${href}">\
                ${mainNavTitles[i].button}\
                </a></li>`);
            } else {
                break;
            }
        }

        $('#mainNav').addClass('navbar navbar-expand-lg navbar-light');
    });
}

步骤3:页面引入文件

<script src="/js/mainNav.js"></script>
<script>
    insertMainNav();
</script>

注意事项

  • 直接用file://协议打开本地HTML时,AJAX可能因跨域限制失败,建议用VS Code的Live Server插件等本地服务器打开页面。
  • 方案1更简单,适合刚入门的你,修改导航只需维护一个配置文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:35:12