使用js在多个页面上显示页眉和页脚

header and footer on multiple pages using js

本文关键字:显示 使用 js      更新时间:2023-09-26

我想使用javascript在html的每一页中调用header.html和footer.html。我试过代码使页眉和页脚文件包含在多个html页面中,但这对我不起作用

这是相同的代码,

<html>
<head>
<title>hi</title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script> 
$("#header").load("header.html"); 
$("#footer").load("footer.html"); 
</script> 
</head>
<body>
<div id="header"></div><br />
<div id="content">
  Main Content
</div><br />
<div id="footer"></div>
</body>
</html>

我从这里下载了jquery-1.11.1.min.jshttp://jquery.com/download/地点请帮我更正这个代码。

您需要将代码包装在文档就绪函数中:

<script>
    jQuery(document).ready(function($){
        $("#header").load("header.html");
        $("#footer").load("footer.html");
    });
</script>

否则,您的代码将在#header#footer可用之前执行。

将代码包装在文档就绪块中

jQuery(document).ready(function($) {
  $('#header').load('header.html', function () {
    console.log('header.html loaded')
  });
  $('#footer').load('footer.html', function () {
    console.log('footer.html loaded')
  });
})

问题是当您调用脚本来加载元素时,您的DOM没有被加载。

Jquery找不到$("#header")和#footer,因为DOM尚未就绪。

</body>标签上方试试这个:

jQuery(document).ready(function($) {
 $("#header").load("header.html"); 
 $("#footer").load("footer.html"); 
}