我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。

在JSF中,我可以这样做:

<ui:include src="b.xhtml" />

这意味着在.xhtml文件中,我可以包含b.xhtml。

我们如何在*.html文件中做到这一点?


当前回答

仅使用HTML是不可能将HTML文件包含在另一个HTML文件中。这里有一个很简单的方法。使用这个JS库你可以很容易地做到这一点。只需使用以下代码:

<script> include('path/to/file.html', document.currentScript) </script>

其他回答

在我看来,最好的解决方案使用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()文档在这里。

这是我的内联解决方案:

(() => { const includes = document.getElementsByTagName('include'); [] .forEach。调用(包含I => { let filePath = i.getAttribute('src'); fetch (filePath)。然后(file => { file.text()。然后(content => { i.insertAdjacentHTML(“afterend”、内容); i.remove (); }); }); }); }) (); FOO < p > < / p > <包括src = " a.html " >加载…< /包括> 酒吧< p > < / p > <包括src = " b.html " >加载…< /包括> < p > t < / p >

目前还没有针对该任务的直接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>  

它是开源的,可能会给你一个想法(我希望)

通过Html5rocks教程检查HTML5导入 在聚合物项目

例如:

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>

基于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($);
        ...
    }
}

Append ->将内容包含到div中

Replace ->替换div

您可以根据相同的设计轻松添加更多的行为