我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
当前回答
通过Html5rocks教程检查HTML5导入 在聚合物项目
例如:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
其他回答
这是一篇很棒的文章,你可以实现公共库,只需使用下面的代码在一行中导入任何HTML文件。
<head>
<link rel="import" href="warnings.html">
</head>
你也可以试试谷歌聚合物
一个非常老的解决方案满足了我当时的需求,但下面是如何做到标准兼容的代码:
<!--[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]-->
插入指定文件的内容。
<!--#include virtual="filename.htm"-->
html5rocks.com has a very good tutorial on this stuff, and this might be a little late, but I myself didn't know this existed. w3schools also has a way to do this using their new library called w3.js. The thing is, this requires the use of a web server and and HTTPRequest object. You can't actually load these locally and test them on your machine. What you can do though, is use polyfills provided on the html5rocks link at the top, or follow their tutorial. With a little JS magic, you can do something like this:
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);
}
This will make the link (Can change to be the wanted link element if already set), set the import (unless you already have it), and then append it. It will then from there take that and parse the file in HTML, and then append it to the desired element under a div. This can all be changed to fit your needs from the appending element to the link you are using. I hope this helped, it may irrelevant now if newer, faster ways have come out without using libraries and frameworks such as jQuery or W3.js.
UPDATE:这将抛出一个错误,表示本地导入已被CORS策略阻塞。可能需要访问深层网络才能使用它,因为深层网络的特性。(意思是没有实际用途)
目前还没有针对该任务的直接HTML解决方案。即使是HTML导入(这是永久的草案)也不会做这件事,因为Import != Include和一些JS魔法无论如何都是需要的。 我最近写了一个VanillaJS脚本,它只是为了将HTML包含到HTML中,没有任何复杂性。
只要放在你的。html中
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
它是开源的,可能会给你一个想法(我希望)