将footer的代码写在footer.html文件中,并且希望在其他HTML文件中引用它而不改变其格式,可以使用JavaScript的fetch函数或者jQuery的$.get函数来异步加载

  1. 在需要引用footer的HTML文件中,创建一个空的<div>元素,用于容纳footer.html文件的内容,如下所示:
<div id="footerContainer"></div>
  • 1.

  1. 在同一个HTML文件中,添加以下JavaScript代码来异步加载并插入footer.html的内容
<!--底部导航栏-->
    <div id="footerContainer"></div>
    <!--            右侧固定栏-->
    <div id="fixbarContainer"></div>
<script>
    function loadAndExecuteHTML(url, containerId, callback) {
        fetch(url)
            .then(response => response.text())
            .then(data => {
                // 添加页面
                document.getElementById(containerId).innerHTML = data;

                // 添加方法
                const scriptTags = document.getElementById(containerId).getElementsByTagName('script');
                for (let i = 0; i < scriptTags.length; i++) {
                    eval.call(window, scriptTags[i].innerHTML);
                }

                // 执行回调函数
                if (typeof callback === 'function') {
                    callback();
                }
            })
            .catch(error => {
                console.error(`An error occurred while loading ${url}:`, error);
            });
    }
    //引入顶部导航栏
    loadAndExecuteHTML('navbar.html', 'navbarContainer');
    //引入底部导航栏
    loadAndExecuteHTML('footer.html', 'footerContainer');
    //引入右侧固定栏
    loadAndExecuteHTML('fixbar.html', 'fixbarContainer');
    //引入步骤条
    loadAndExecuteHTML('stepFom.html', 'stepContainer');
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.