【问题标题】:header and footer on multiple pages using js使用js在多个页面上的页眉和页脚
【发布时间】:2014-11-13 02:58:23
【问题描述】:

我想使用 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。请帮助我更正此代码。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

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

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

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

【讨论】:

  • 嗨,这适用于 mozilla 但不适用于 chrome
  • 嗨,我检查了控制台。这是错误 XMLHttpRequest 无法加载 header.html。收到无效回复。因此,Origin 'null' 不允许访问。 index.html:1 header.html 已加载
  • 这段代码没有问题 - 这是因为您使用的是带有文件 URL 的 chrome。 stackoverflow.com/questions/4208530/…
【解决方案2】:

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

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

【讨论】:

  • 嗨,这适用于 mozilla 但不适用于 chrome –
【解决方案3】:

问题是当你调用脚本加载元素时你的DOM没有加载。

Jquery 找不到 $("#header") 和 #footer,因为 DOM 尚未准备好。

&lt;/body&gt; 标签上方试试这个:

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

【讨论】:

  • 嗨,这适用于 mozilla 但不适用于 chrome –
猜你喜欢
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多