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

时间:2014-11-12 18:49:33

标签: javascript jquery html

我想使用javascript在html的每个页面中调用header.html和footer.html。我试过了 代码Make header and footer files to be included in multiple html pages,但这对我不起作用

这是相同的代码,

<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>

我从这个http://jquery.com/download/网站下载了jquery-1.11.1.min.js。请帮我修正一下这段代码。

3 个答案:

答案 0 :(得分:2)

您需要将代码包装在document ready函数中:

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

问题是,当您调用脚本加载元素时,您的DOM未加载。

Jquery无法找到$(“#header”)和#footer,因为DOM尚未就绪。

</body>标记上方试试:

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