我有2个HTML文件,假设a.html
和b.html
。在a.html
我想要包含b.html
。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在a.xhtml
文件中,我可以包含b.xhtml
。
我们如何在*.html
档案中执行此操作?
答案 0 :(得分:623)
在我看来,最好的解决方案是使用jQuery:
a.html
:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html
:
<p>This is my include file</p>
这个方法对我的问题来说是一个简单而干净的解决方案。
jQuery .load()
文档为here。
答案 1 :(得分:132)
我的解决方案类似于上面lolo的解决方案。但是,我通过JavaScript的document.write插入HTML代码而不是使用jQuery:
<强> a.html:强>
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
<强> b.js:强>
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
我反对使用jQuery的原因是jQuery.js的大小约为90kb,我希望尽可能减少加载的数据量。
为了在没有太多工作的情况下获取正确转义的JavaScript文件,您可以使用以下sed命令:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
或者只使用在Github上作为Gist发布的以下方便的bash脚本,自动执行所有必要的工作,将b.html
转换为b.js
:
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
致Greg Minshall的改进的sed命令,它也逃脱了反斜杠和单引号,这是我原来的sed命令没有考虑的。
答案 2 :(得分:127)
从上面扩展lolo的答案,如果你需要包含大量文件,这里有一点自动化:
diff = then - now
然后在html中包含一些内容:
In [12]: diff
Out[12]: Timedelta('-1 days +23:00:00')
In [13]: diff.seconds
Out[13]: 82800
In [14]: diff.total_seconds()
Out[14]: -3600.0
其中包括文件views / header.html和views / footer.html
答案 3 :(得分:80)
结帐HTML5导入via Html5rocks tutorial 并在polymer-project
例如:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
答案 4 :(得分:57)
我编写的库的无耻插件解决了这个问题。
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
以上内容将采用/path/to/include.html
的内容,并将div
替换为{。}}。
答案 5 :(得分:43)
一个简单的服务器端include指令包含在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
答案 6 :(得分:33)
A very old solution我当时确实满足了我的需求,但这里是如何做到符合标准的代码:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
答案 7 :(得分:30)
不需要脚本。不需要在服务器端做任何花哨的东西(这可能是更好的选择)
<iframe src="/path/to/file.html" seamless></iframe>
由于旧浏览器不支持无缝,因此您应该添加一些css来修复它:
iframe[seamless] {
border: none;
}
请注意,对于不支持无缝的浏览器,如果您点击iframe中的链接,则会使框架转到该网址,而不是整个窗口。解决这个问题的方法是让所有链接都有target="_parent"
,浏览器支持“足够好”。
答案 8 :(得分:16)
作为替代方案,如果您可以访问服务器上的.htaccess文件,则可以添加一个简单的指令,允许在以.html扩展名结尾的文件上解析php。
RemoveHandler .html
AddType application/x-httpd-php .php .html
现在您可以使用简单的PHP脚本来包含其他文件,例如:
<?php include('b.html'); ?>
答案 9 :(得分:14)
如果需要包含来自某个文件的html内容,以下作品: 例如,以下行将在OBJECT定义发生的位置包含piece_to_include.html的内容。
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
参考:http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
答案 10 :(得分:9)
这对我有所帮助。要将b.html
的html代码块添加到a.html
,请将其放入head
的{{1}}标记中:
a.html
然后在body标签中,使用唯一ID和javascript块创建一个容器,将<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
加载到容器中,如下所示:
b.html
答案 11 :(得分:8)
我知道这是一个非常古老的帖子,所以当时没有一些方法可用。 但这是我非常简单的看法(根据Lolo的答案)。
它依赖于HTML5 data- *属性,因此非常通用,因为它使用jQuery来实现每个.class匹配&#34; load-html&#34;并使用其各自的数据源&#39;要加载内容的属性:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
答案 12 :(得分:8)
您可以使用HTML Imports(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)或该简化解决方案的polyfill https://github.com/dsheiko/html-import
例如,在页面上导入HTML块,如下所示:
<link rel="html-import" href="./some-path/block.html" >
该块可能具有自己的导入:
<link rel="html-import" href="./some-other-path/other-block.html" >
导入器将指令替换为加载的HTML,非常类似于SSI
加载这个小型JavaScript后,这些指令将自动提供:
<script async src="./src/html-import.js"></script>
当DOM自动准备好时,它将处理导入。此外,它还公开了一个可用于手动运行,获取日志等的API。享受:)
答案 13 :(得分:6)
在w3.js中包含这样的作品:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
如需正确说明,请查看:https://www.w3schools.com/howto/howto_html_include.asp
答案 14 :(得分:5)
Athari的答案(第一个!)太确定了!很好!
但是,如果你想传递要包含在网址中的网页名称,这篇文章有一个非常好的解决方案可以与以下内容结合使用:
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
所以它变成了这样:
您的网址:
www.yoursite.com/a.html?p=b.html
a.html 代码现在变为:
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
对我来说效果很好! 我希望有所帮助:)
答案 15 :(得分:5)
大多数解决方案都有效,但它们存在 jquery :
的问题问题在于代码$(document).ready(function () { alert($("#includedContent").text()); }
不提醒任何内容,而是警告包含的内容。
我编写以下代码,在我的解决方案中,您可以访问$(document).ready
函数中包含的内容:
(关键是同步加载包含的内容)。
<强>的index.htm 强>:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
<强> include.inc 强>:
<div id="test">
There is no issue between this solution and jquery.
</div>
答案 16 :(得分:5)
插入指定文件的内容:
<!--#include virtual="filename.htm"-->
答案 17 :(得分:4)
html5rocks.com有一个关于这个东西的非常好的教程,这可能有点晚了,但我自己并不知道这个存在。 w3schools还有一种方法可以使用名为w3.js的新库。问题是,这需要使用Web服务器和HTTPRequest对象。您无法在本地加载这些文件并在您的计算机上进行测试。你可以做的是使用顶部html5rocks链接提供的polyfill,或者按照他们的教程。有了一点JS魔法,你可以这样做:
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
这将生成链接(如果已经设置,可以更改为想要的链接元素),设置导入(除非您已经拥有它),然后追加它。然后它将从那里获取并以HTML格式解析文件,然后将其附加到div下的所需元素。这一切都可以根据您的需要从附加元素更改为您正在使用的链接。我希望这有所帮助,如果没有使用jQuery或W3.js这样的库和框架,更新,更快的方法出现可能无关紧要。
更新:这会抛出错误,说明本地导入已被CORS策略阻止。由于深层网络的属性,可能需要访问深层网络以便能够使用它。 (意思没有实际用途)
答案 18 :(得分:3)
目前没有针对此任务的直接HTML解决方案。即使HTML Imports(在草稿中永久)也不会做这件事,因为导入!=包含并且无论如何都需要一些JS魔术。
我最近写了a VanillaJS script,它只是将HTML包含在HTML中,没有任何复杂性。
只需放入a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
这是open-source
,可能会提出一个想法(我希望)
答案 19 :(得分:3)
这是我的就地解决方案:
(() => {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, i => {
let filePath = i.getAttribute('src');
fetch(filePath).then(file => {
file.text().then(content => {
i.insertAdjacentHTML('afterend', content);
i.remove();
});
});
});
})();
<p>FOO</p>
<include src="a.html">Loading...</include>
<p>BAR</p>
<include src="b.html">Loading...</include>
<p>TEE</p>
答案 20 :(得分:1)
这是我使用Fetch API和异步函数的方法
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
答案 21 :(得分:1)
我还有另一种解决方案
在javascript中使用Ajax
这是Github回购中的解释代码 https://github.com/dupinder/staticHTML-Include
基本思想是:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='main.js'></script>
</head>
<body>
<header></header>
<footer></footer>
</body>
</html>
main.js
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
答案 22 :(得分:1)
Here is a great article,您可以实现公共库,只需使用下面的代码即可在一行中导入任何HTML文件。
<head>
<link rel="import" href="warnings.html">
</head>
您还可以尝试Google Polymer
答案 23 :(得分:1)
我创建了类似于JSF的以下web_accessible_resources
<ui-include src="b.xhtml"><ui-include>
您web-component作为页面内的常规html标签(包括代码段js代码之后)
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
ui-include { margin: 20px } /* example CSS */
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>
<div>My page data... - in this snippet styles overlaps...</div>
<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>
答案 24 :(得分:0)
仅使用HTML,就不可能在另一个 HTML 文件中包含 HTML 文件。但这是一种非常简单的方法。 Using this JS library,您可以轻松做到这一点。只需使用以下代码:
<script> include('path/to/file.html', document.currentScript) </script>
答案 25 :(得分:0)
您尝试过iFrame注入吗?
它将iFrame注入文档中并删除自身(应该在HTML DOM中被删除)
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
致谢
答案 26 :(得分:0)
无论您的项目是否为AngularJS,我都强烈建议AngularJS的ng-include
。
<script src=".../angular.min.js"></script>
<body ng-app="ngApp" ng-controller="ngCtrl">
<div ng-include="'another.html'"></div>
<script>
var app = angular.module('ngApp', []);
app.controller('ngCtrl', function() {});
</script>
</body>
答案 27 :(得分:0)
要使解决方案正常工作,您需要包含文件csi.min.js,您可以在其中找到here。
按照GitHub上显示的示例,要使用此库,必须在页面标题中包含文件csi.js,然后需要将data-include属性及其值设置添加到要包含的文件中,在容器元素上。
隐藏复制代码
<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>
...希望有帮助。
答案 28 :(得分:0)
以上所有解决方案都没有允许JS定位到新包含的HTML的事件挂钩。许多浏览器也不兼容。
因此,我为可能需要比简单的HTML包含脚本具有这两个优点的任何人创建了一个库。
这是JS库:includeme.js
答案 29 :(得分:0)
将Fetch API与Promise结合使用的另一种方法
<html>
<body>
<div class="root" data-content="partial.html">
<script>
const root = document.querySelector('.root')
const link = root.dataset.content;
fetch(link)
.then(function (response) {
return response.text();
})
.then(function (html) {
root.innerHTML = html;
});
</script>
</body>
</html>
答案 30 :(得分:0)
使用 ES6反引号``:template literals!
let nick = "Castor", name = "Moon", nuts = 1
more.innerHTML = `
<h1>Hello ${nick} ${name}!</h1>
You collected ${nuts} nuts so far!
<hr>
Double it and get ${nuts + nuts} nuts!!
`
<div id="more"></div>
这样,我们可以包含不带引号的html,包含DOM中的变量等等。
这是一个功能强大的模板引擎,我们可以使用单独的js文件并使用事件将内容加载到位,甚至可以将所有内容分成块并按需调用:
let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);
答案 31 :(得分:0)
根据https://stackoverflow.com/a/31837264/4360308的答案 我已经使用Nodejs(+ express + cheerio)实现了这个功能,如下所示:
HTML(index.html)
<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>
<强> JS 强>
function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}
function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}
追加 - &gt;将内容包含在div中
替换 - &gt;替换div
您可以根据相同的设计轻松添加更多行为
答案 32 :(得分:0)
如果你使用像django / bootle这样的框架,他们经常会发布一些模板引擎。 我们假设你使用瓶子,默认模板引擎是SimpleTemplate Engine。 以下是纯HTML文件
$ cat footer.tpl
<hr> <footer> <p>© stackoverflow, inc 2015</p> </footer>
您可以在主文件中包含footer.tpl,例如:
$ cat dashboard.tpl
%include footer
除此之外,您还可以将参数传递给dashborard.tpl。
答案 33 :(得分:0)
PHP是一种服务器级脚本语言。它可以做很多事情,但一种流行的用法是在页面中包含HTML文档,与SSI非常相似。与SSI一样,这是一种服务器级技术。如果您不确定您的网站上是否有PHP功能,请与您的托管服务提供商联系。
这是一个简单的PHP脚本,您可以使用它在任何支持PHP的网页上包含HTML代码段:
将网站常用元素的HTML保存为单独的文件。例如,您的导航部分可能会保存为navigation.html或navigation.php。 使用以下PHP代码在每个页面中包含该HTML。
<?php require($DOCUMENT_ROOT . "navigation.php"); ?>
在要包含该文件的每个页面上使用相同的代码。 确保将已突出显示的文件名更改为包含文件的名称和路径。
答案 34 :(得分:0)
我来到这个主题寻找类似的东西,但与lolo提出的问题略有不同。我想构建一个HTML页面,其中包含指向其他页面的链接的字母菜单,并且每个其他页面可能存在也可能不存在,并且创建它们的顺序可能不是按字母顺序排列的(甚至也不是数字)。另外,像Tafkadasoh一样,我不想用jQuery膨胀网页。在研究了这个问题并进行了几个小时的实验之后,这对我有用,并附上相关评论:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
<meta name="Author" content="me">
<meta copyright="Copyright" content= "(C) 2013-present by me" />
<title>Menu</title>
<script type="text/javascript">
<!--
var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
var dat = new Array();
var form, script, write, str, tmp, dtno, indx, unde;
/*
The "F000" and similar variables need to exist/be-declared.
Each one will be associated with a different menu item,
so decide on how many items maximum you are likely to need,
when constructing that listing of them. Here, there are 20.
*/
function initialize()
{ window.name="Menu";
form = document.getElementById('MENU');
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = str.substr(tmp);
script = document.createElement('script');
script.type = 'text/javascript';
script.src = str + ".js";
form.appendChild(script);
}
/*
The for() loop constructs some <script> objects
and associates each one with a different simple file name,
starting with "000.js" and, here, going up to "019.js".
It won't matter which of those files exist or not.
However, for each menu item you want to display on this
page, you will need to ensure that its .js file does exist.
The short function below (inside HTML comment-block) is,
generically, what the content of each one of the .js files looks like:
<!--
function F000()
{ return ["Menu Item Name", "./URLofFile.htm", "Description string"];
}
-->
(Continuing the remarks in the main menu.htm file)
It happens that each call of the form.appendChild() function
will cause the specified .js script-file to be loaded at that time.
However, it takes a bit of time for the JavaScript in the file
to be fully integrated into the web page, so one thing that I tried,
but it didn't work, was to write an "onload" event handler.
The handler was apparently being called before the just-loaded
JavaScript had actually become accessible.
Note that the name of the function in the .js file is the same as one
of the the pre-defined variables like "F000". When I tried to access
that function without declaring the variable, attempting to use an
"onload" event handler, the JavaScript debugger claimed that the item
was "not available". This is not something that can be tested-for!
However, "undefined" IS something that CAN be tested-for. Simply
declaring them to exist automatically makes all of them "undefined".
When the system finishes integrating a just-loaded .js script file,
the appropriate variable, like "F000", will become something other
than "undefined". Thus it doesn't matter which .js files exist or
not, because we can simply test all the "F000"-type variables, and
ignore the ones that are "undefined". More on that later.
The line below specifies a delay of 2 seconds, before any attempt
is made to access the scripts that were loaded. That DOES give the
system enough time to fully integrate them into the web page.
(If you have a really long list of menu items, or expect the page
to be loaded by an old/slow computer, a longer delay may be needed.)
*/
window.setTimeout("BuildMenu();", 2000);
return;
}
//So here is the function that gets called after the 2-second delay
function BuildMenu()
{ dtno = 0; //index-counter for the "dat" array
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = "F" + str.substr(tmp);
tmp = eval(str);
if(tmp != unde) // "unde" is deliberately undefined, for this test
dat[dtno++] = eval(str + "()");
}
/*
The loop above simply tests each one of the "F000"-type variables, to
see if it is "undefined" or not. Any actually-defined variable holds
a short function (from the ".js" script-file as previously indicated).
We call the function to get some data for one menu item, and put that
data into an array named "dat".
Below, the array is sorted alphabetically (the default), and the
"dtno" variable lets us know exactly how many menu items we will
be working with. The loop that follows creates some "<span>" tags,
and the the "innerHTML" property of each one is set to become an
"anchor" or "<a>" tag, for a link to some other web page. A description
and a "<br />" tag gets included for each link. Finally, each new
<span> object is appended to the menu-page's "form" object, and thereby
ends up being inserted into the middle of the overall text on the page.
(For finer control of where you want to put text in a page, consider
placing something like this in the web page at an appropriate place,
as preparation:
<div id="InsertHere"></div>
You could then use document.getElementById("InsertHere") to get it into
a variable, for appending of <span> elements, the way a variable named
"form" was used in this example menu page.
Note: You don't have to specify the link in the same way I did
(the type of link specified here only works if JavaScript is enabled).
You are free to use the more-standard "<a>" tag with the "href"
property defined, if you wish. But whichever way you go,
you need to make sure that any pages being linked actually exist!
*/
dat.sort();
for(indx=0; indx<dtno; indx++)
{ write = document.createElement('span');
write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] +
"', 'Menu');\" style=\"color:#0000ff;" +
"text-decoration:underline;cursor:pointer;\">" +
dat[indx][0] + "</a> " + dat[indx][2] + "<br />";
form.appendChild(write);
}
return;
}
// -->
</script>
</head>
<body onload="initialize();" style="background-color:#a0a0a0; color:#000000;
font-family:sans-serif; font-size:11pt;">
<h2>
MENU
<noscript><br /><span style="color:#ff0000;">
Links here only work if<br />
your browser's JavaScript<br />
support is enabled.</span><br /></noscript></h2>
These are the menu items you currently have available:<br />
<br />
<form id="MENU" action="" onsubmit="return false;">
<!-- Yes, the <form> object starts out completely empty -->
</form>
Click any link, and enjoy it as much as you like.<br />
Then use your browser's BACK button to return to this Menu,<br />
so you can click a different link for a different thing.<br />
<br />
<br />
<small>This file (web page) Copyright (c) 2013-present by me</small>
</body>
</html>
答案 35 :(得分:-6)
使用jquery你需要导入库
我建议你使用php
<?php
echo"<html>
<body>";
?>
<?php
include "b.html";
?>
<?php
echo" </body>
</html>";
?>
b.html
<div>hi this is ur file :3<div>