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

如何用一行代码在多HTML文件中通过jQuery统一加载页脚内容?

简化多HTML文件的页脚加载代码

需求

在多个HTML文件中,每次都要复制多行代码引入jQuery并加载footer.html展示页脚标语,希望简化为<head>中的一行代码,避免重复操作。

当前代码示例

主HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
<title>Dunlavy US Home Page</title>
<link rel="stylesheet" type="text/css" href="common.css">

<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script> 
$(function(){
$("#footer").load("footer.html"); 
});
</script> 

</head>
<body>
<h2>This is a sample of a copied bottom line of text using jquery.
<br>
It Works Good.
</h2>
<br>
<div id="footer"></div>
</body>
</html>
<p>Copyright &copy; 1999-2024 . Professional Systems Industries, by 3d</p>

解决方案

把jQuery引入和页脚加载逻辑封装到单独的JS文件中,之后每个HTML文件只需引入这个JS文件即可,实现一行代码搞定。

将以下代码保存为load-footer.js(和HTML文件放在同一目录):

// 动态加载jQuery库
const jqueryScript = document.createElement('script');
jqueryScript.src = 'https://code.jquery.com/jquery-3.3.1.js';
jqueryScript.integrity = 'sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=';
jqueryScript.crossOrigin = 'anonymous';

// jQuery加载完成后执行页脚加载逻辑
jqueryScript.onload = function() {
    $(function() {
        $("#footer").load("footer.html");
    });
};

// 将脚本添加到页面头部
document.head.appendChild(jqueryScript);

步骤2:修改主HTML文件

把原来<head>中的两行<script>代码替换为一行:

<script src="load-footer.js"></script>

修改后的主HTML头部示例:

<head>
<title>Dunlavy US Home Page</title>
<link rel="stylesheet" type="text/css" href="common.css">
<script src="load-footer.js"></script>
</head>

注意事项

  • 确保load-footer.js和HTML文件路径正确,若放在子目录需调整src路径,比如src="js/load-footer.js"。
  • 每个需要加载页脚的HTML文件,必须保留<div id="footer"></div>容器。
  • footer.html的位置保持不变,确保路径可被正确访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:43:14