jQuery 使页眉和页脚文件包含在多个 html 页面中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18712338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make header and footer files to be included in multiple html pages
提问by Prasanth A R
I want to create common header and footer pages that are included on several html pages.
我想创建包含在多个 html 页面中的常见页眉和页脚页面。
I'd like to use javascript. Is there a way to do this using only html and JavaScript?
我想使用javascript。有没有办法只使用 html 和 JavaScript 来做到这一点?
I want to load a header and footer page within another html page.
我想在另一个 html 页面中加载页眉和页脚页面。
回答by Hariprasad Prolanx
You can accomplish this with jquery.
您可以使用jquery完成此操作。
Place this code in index.html
将此代码放入 index.html
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
and put this code in header.html
and footer.html
, at the same location as index.html
并将此代码放入header.html
和footer.html
,与index.html
<a href="http://www.google.com">click here for google</a>
Now, when you visit index.html
, you should be able to click the link tags.
现在,当您访问 时index.html
,您应该能够点击链接标签。
回答by The Conspiracy
I add common parts as header and footer using Server Side Includes. No HTML and no JavaScript is needed. Instead, the webserver automatically adds the included code before doing anything else.
我使用Server Side Includes添加公共部分作为页眉和页脚。不需要 HTML 和 JavaScript。相反,网络服务器会在执行任何其他操作之前自动添加包含的代码。
Just add the following line where you want to include your file:
只需在要包含文件的位置添加以下行:
<!--#include file="include_head.html" -->
回答by Sol
Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?
你必须在 JavaScript 中使用 html 文件结构吗?您是否考虑过使用 PHP 来代替简单的 PHP 包含对象?
If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php
如果您将 .html 页面的文件名转换为 .php - 那么在每个 .php 页面的顶部,您可以使用一行代码来包含 header.php 中的内容
<?php include('header.php'); ?>
Do the same in the footer of each page to include the content from your footer.php file
在每个页面的页脚中执行相同的操作以包含您的 footer.php 文件中的内容
<?php include('footer.php'); ?>
No JavaScript / Jquery or additional included files required.
不需要 JavaScript / Jquery 或其他包含的文件。
NB You could also convert your .html files to .php files using the following in your .htaccess file
注意您还可以使用 .htaccess 文件中的以下内容将 .html 文件转换为 .php 文件
# re-write html to php
RewriteRule ^(.*)\.html$ .php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/ [R=301,L]
# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ .php [NC,L]
回答by Asheesh Gupta
I tried this: Create a file header.htmllike
我试过这个:像创建一个文件header.html
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.htmlin your HTML pages like:
现在在您的 HTML 页面中包含header.html,例如:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
工作得很好。
回答by JustinM
You could also put: (load_essentials.js:)
你也可以放:(load_essentials.js:)
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
回答by JavierFuentes
I think, answers to this question are too old... currently some desktop and mobile browsers support HTML Templatesfor doing this.
我认为,这个问题的答案太旧了……目前一些桌面和移动浏览器支持HTML 模板来执行此操作。
I've built a little example:
我已经建立了一个小例子:
Tested OKin Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 and Adblocker Browser 54.0
Tested KOin Safari 10.1, Firefox 56.0, Edge 38.14 and IE 11
测试行中铬61.0,歌剧48.0,歌剧霓虹灯1.0,Android浏览器6.0,铬61.0移动和Adblocker浏览器54.0
测试KO在Safari 10.1,火狐56.0,边缘38.14和IE 11
More compatibility info in canisue.com
canisue.com 中的更多兼容性信息
index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
Your can get more examples in this HTML5 Rocks post
您可以在此HTML5 Rocks 帖子中获得更多示例
回答by darcher
I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.
我一直在使用 C#/Razor,因为我的家用笔记本电脑上没有 IIS 设置,所以我寻找一个 javascript 解决方案来加载视图,同时为我们的项目创建静态标记。
I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.
我偶然发现了一个解释“抛弃 jquery”方法的网站,它演示了该网站上的一种方法,它完全符合您在普通 Jane javascript 中所追求的功能(帖子底部的参考链接)。如果您打算在生产中使用它,请务必调查任何安全漏洞和兼容性问题。我不是,所以我自己从来没有研究过。
JS Function
JS函数
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
Get the content
获取内容
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
index.html
索引.html
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
views/header.html
视图/header.html
<!-- This element will replace #header -->
<header id="new-header"></header>
The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page
来源不是我自己的,我只是引用它,因为它是 OP 的一个很好的 vanilla javascript 解决方案。原始代码在这里:http: //gomakethings.com/ditching-jquery#get-html-from-another-page
回答by Mark
Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.
Aloha 从 2018 年开始。不幸的是,我没有任何很酷或未来主义的东西可以与您分享。
I did however want to point out to those who have commented that the jQuery load()
method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http
, data
, or https
. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)
然而,我确实想指出那些评论 jQueryload()
方法目前不起作用的人可能试图在不运行本地 Web 服务器的情况下将方法与本地文件一起使用。这样做会抛出上述“跨源”的错误,它指定了跨源请求诸如由负载方法制备的仅支持的协议方案等http
,data
或 https
。(我假设您没有发出实际的跨域请求,即 header.html 文件实际上与您从中请求的页面位于同一域中)
So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.
因此,如果上面接受的答案对您不起作用,请确保您正在运行网络服务器。如果您赶时间(并且使用预装了 Python 的 Mac),最快捷、最简单的方法是启动一个简单的 Python http 服务器。您可以在这里看到这样做是多么容易。
I hope this helps!
我希望这有帮助!
回答by Samuel Omopariola
It is also possible to load scripts and links into the header. I'll be adding it one of the examples above...
还可以将脚本和链接加载到标题中。我将把它添加到上面的例子之一......
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
回答by Mitch VanDuyn
another approach made available since this question was first asked is to use reactrb-express (see http://reactrb.org) This will let you script in ruby on the client side, replacing your html code with react components written in ruby.
自从首次提出这个问题以来,另一种可用的方法是使用 reactrb-express(参见http://reactrb.org)这将让您在客户端用 ruby 编写脚本,用用 ruby 编写的 react 组件替换您的 html 代码。