提问人:lolo 提问时间:1/24/2012 最后编辑:Kamil Kiełczewskilolo 更新时间:8/28/2023 访问量:2082023
在 HTML 文件中包含另一个 HTML 文件
Include another HTML file in a HTML file
问:
我有 2 个 HTML 文件,假设和 .在我想包括 .a.html
b.html
a.html
b.html
在 JSF 中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在文件中,我可以包括 .a.xhtml
b.xhtml
我们怎样才能在文件中做到这一点?*.html
答:
或者,如果您有权访问服务器上的 .htaccess 文件,您可以添加一个简单的指令,允许在以 .html 扩展名结尾的文件上解释 php。
RemoveHandler .html
AddType application/x-httpd-php .php .html
现在,您可以使用简单的 php 脚本来包含其他文件,例如:
<?php include('b.html'); ?>
评论
.htaccess
可能会导致 html
页面尝试下载为文件,而不是在浏览器中查看。首先测试。 免责声明:当我尝试上述解决方案时,这刚刚发生在我身上。除了上面两行外,我的 .htaccess
是空的。建议谨慎。试试lolo
的jQuery解决方案(如下)。
在我看来,最好的解决方案是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()
评论
$(function(){})
XMLHttpRequest cannot load file:///.../b.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
我的解决方案类似于上面的 lolo。但是,我通过 JavaScript 的 document.write 而不是使用 jQuery 插入 HTML 代码:
一个 .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
或者只是使用以下方便的 bash 脚本作为 Gist,在 Github 上发布,它可以自动执行所有必要的工作,转换为: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6b.html
b.js
感谢 Greg Minshall 改进的 sed 命令,该命令也转义了反斜杠和单引号,而我原来的 sed 命令没有考虑这些。
或者,对于支持模板文字的浏览器,以下操作也有效:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
评论
'
` with
'
\'
一个简单的服务器端 include 指令,用于包含在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
您也可以尝试:
<!--#include file="a.html" -->
评论
<!--#include file="a.html" -->
web.config
<handlers>
我当时做的一个非常古老的解决方案满足了我的需求,但以下是如何做到符合标准的代码:
<!--[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]-->
评论
<object>
<embed>
<iframe>
seamless
seamless
要插入命名文件的内容,请执行以下操作:
<!--#include virtual="filename.htm"-->
评论
无需脚本。无需在服务器端做任何花哨的事情(这可能是一个更好的选择)
<iframe src="/path/to/file.html" seamless></iframe>
由于旧浏览器不支持无缝,您应该添加一些 css 来修复它:
iframe[seamless] {
border: none;
}
请记住,对于不支持无缝的浏览器,如果您单击 iframe 中的链接,它将使框架转到该 URL,而不是整个窗口。解决此问题的一种方法是让所有链接都具有,浏览器支持“足够好”。target="_parent"
评论
阿塔里人的回答(第一个!)太有说服力了!非常好!
但是,如果您想将要包含的页面名称作为 URL 参数传递,这篇文章有一个非常好的解决方案可以与以下组合使用:
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>
它对我来说效果很好! 我希望对:)有所帮助
评论
我写的一个图书馆的无耻插件解决了这个问题。
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
上面将获取 的内容并用它替换。/path/to/include.html
div
评论
<div data-include="/path/to/include.html"></div>
通过 Html5rocks 教程和 polymer-project 查看 HTML5 导入
例如:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
评论
stuff.html
如果需要包含某些文件中的 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
评论
大多数解决方案都有效,但它们存在jquery问题:
问题在于代码之后什么都不会发出警报,而不是对包含的内容发出警报。$(document).ready(function () { alert($("#includedContent").text()); }
我编写了以下代码,在我的解决方案中,您可以访问函数中包含的内容:$(document).ready
(关键是同步加载包含的内容)。
索引:.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>
评论
目前没有针对该任务的直接 HTML 解决方案。即使是 HTML Imports(永久处于草稿状态)也无法做到这一点,因为无论如何都需要 Import != Include 和一些 JS 魔法。
我最近编写了一个 VanillaJS 脚本,它只是为了将 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
这是一篇很棒的文章,您可以实现通用库,只需使用下面的代码即可在一行中导入任何 HTML 文件。
<head>
<link rel="import" href="warnings.html">
</head>
您也可以尝试 Google Polymer
评论
import
link
扩展 lolo 的答案,如果您必须包含大量文件,这里会有更多的自动化。使用以下 JS 代码:
$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})
然后在 html 中包含一些内容:
<div data-include="header"></div>
<div data-include="footer"></div>
这将包括文件和 .views/header.html
views/footer.html
评论
data-argument
$("#postdiv").load('posts.php?name=Test&age=25');
你可以用 JavaScript 的库 jQuery 做到这一点,如下所示:
HTML格式:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
请注意,该文件应位于您的其他页面所在的同一域下,否则您的网页将因跨域资源共享策略而拒绝该文件。banner.html
banner.html
另外,请注意,如果您使用 JavaScript 加载内容,Google 将无法将其编入索引,因此出于 SEO 原因,这并不是一个好方法。
html5rocks.com 有一个关于这个东西的非常好的教程,这可能有点晚了,但我自己并不知道它的存在。W3Schools也有一种方法可以使用他们的新库W3.js来做到这一点。问题是,这需要使用 Web 服务器和 HTTPRequest 对象。您实际上无法在本地加载这些内容并在计算机上测试它们。不过,您可以做的是使用顶部 html5rocks 链接中提供的 polyfills,或按照他们的教程进行操作。只要有一点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 策略阻止。由于深网的属性,可能需要访问深网才能使用它。(表示没有实际用途)
这就是帮助我的原因。要添加 html 代码块 from to ,这应该进入 :b.html
a.html
head
a.html
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
然后在 body 标签中,使用唯一 id 和 javascript 块创建一个容器,用于将 load 到容器中,如下所示:b.html
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
评论
在 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
评论
您可以使用 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,您可以使用该 API 手动运行、获取日志等。享受:)
评论
我知道这是一个非常古老的帖子,所以当时没有一些方法。 但这是我对它非常简单的看法(基于 Lolo 的回答)。
它依赖于 HTML5 data-* 属性,因此非常通用,因为它使用 jQuery 的 for-each 函数来获取每个匹配的 .class “load-html”,并使用其各自的“data-source”属性来加载内容:
<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>
这是我使用 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>
评论
将 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>
要使解决方案正常工作,您需要包含文件 csi.min.js,您可以在此处找到该文件。
根据 GitHub 上显示的示例,要使用此库,您必须在页面标题中包含文件 csi.js,然后您需要在容器元素上添加 data-include 属性,并将其值设置为要包含的文件。
隐藏复制代码
<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>
...希望它有所帮助。
评论
您是否尝试过 iFrame 注入?
它将 iFrame 注入文档并删除自身(它应该在 HTML DOM 中)
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
问候
评论
这是我的内联解决方案:
(() => {
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>
评论
Web 组件
我创建了类似于 JSF 的以下 Web 组件
<ui-include src="b.xhtml"><ui-include>
您可以将其用作页面中的常规 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>
(StackOverflow 片段会更好地工作(加载整个页面,而不仅仅是消息)当你第一次去这里并按下按钮让你的计算机临时访问 CORS-Anywhere 时)
评论
display: contents
使用 includeHTML(最小 js-lib:~150 行)
通过 HTML 标记加载 HTML 部分(纯 js)
支持的加载:异步/同步,任何深度递归包括
支持的协议:http://、https://、file:///
支持的浏览器:IE 9+、FF、Chrome(也可能是其他)
用法:
1.在HTML文件中将includeHTML插入到head部分(或正文关闭标记之前):
<script src="js/includeHTML.js"></script>
2.随处使用includeHTML作为HTML标签:
<div data-src="header.html"></div>
评论
file://
alert()
这里有几种类型的答案,但我从未在这里找到最古老的工具:
“所有其他答案都对我不起作用。”
<html>
<head>
<title>pagetitle</title>
</head>
<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
<frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">
</frameset>
</html>
评论
这些解决方案都不适合我的需求。我一直在寻找更像PHP的东西。在我看来,这个解决方案非常简单和高效。
include.js
->
void function(script) {
const { searchParams } = new URL(script.src);
fetch(searchParams.get('src')).then(r => r.text()).then(content => {
script.outerHTML = content;
});
}(document.currentScript);
index.html
->
<script src="/include.js?src=/header.html">
<main>
Hello World!
</main>
<script src="/include.js?src=/footer.html">
可以进行简单的调整以创建 、 和 ,根据您正在执行的操作,这些调整可能都很有用。下面是一个简短的示例。include_once
require
require_once
include_once
->
var includedCache = includedCache || new Set();
void function(script) {
const { searchParams } = new URL(script.src);
const filePath = searchParams.get('src');
if (!includedCache.has(filePath)) {
fetch(filePath).then(r => r.text()).then(content => {
includedCache.add(filePath);
script.outerHTML = content;
});
}
}(document.currentScript);
希望对你有所帮助!
评论
localhost
<script> $(function(){ $("#includedNavigation").load("navigation.html"); }); </script>