在HTML文件中包含另一个HTML文件

2020/09/22 22:41 · javascript ·  · 0评论

我有2个HTML文件,假设是a.htmlb.htmla.html我想包括b.html

在JSF中,我可以这样做:

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

这意味着在a.xhtml文件内部,我可以包含b.xhtml

我们该如何*.html归档?

我认为最好的解决方案是使用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()文档在这里

从上面扩展lolo的答案,如果您必须包含很多文件,则这里的自动化程度更高:

<script>
  $(function(){
    var includes = $('[data-include]');
    jQuery.each(includes, function(){
      var file = 'views/' + $(this).data('include') + '.html';
      $(this).load(file);
    });
  });
</script>

然后在html中包含一些内容:

<div data-include="header"></div>
<div data-include="footer"></div>

其中将包含文件views / header.html和views / footer.html

我的解决方案类似于上面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.htmlb.jshttps :
//gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

学分格雷格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>

`);

通过Html5rocks教程
Polymer-Project检出HTML5导入

例如:

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

我写的库的无耻插件解决了这个问题。

https://github.com/LexmarkWeb/csi.js

<div data-include="/path/to/include.html"></div>

上面的内容将采用的内容/path/to/include.html并将其替换div

一个简单的服务器端include指令,其中包含在同一文件夹中找到的另一个文件,如下所示:

<!--#include virtual="a.html" --> 

无需脚本。不需要在服务器端做任何花哨的东西(这可能是一个更好的选择)

<iframe src="/path/to/file.html" seamless></iframe>

由于旧的浏览器不支持无缝,因此您应该添加一些CSS来修复它:

iframe[seamless] {
    border: none;
}

请记住,对于不支持无缝浏览器的浏览器,如果单击iframe中的链接,它将使该框架转到该URL,而不是整个窗口。解决该问题的一种方法是让所有链接都拥有target="_parent",而浏览器的支持“足够好”。

当时我确实满足了我的需求,这是一个非常老的解决方案,但是下面是如何实现符合标准的代码:

<!--[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]-->

或者,如果您有权访问服务器上的.htaccess文件,则可以添加一个简单的指令,该指令将允许以.html扩展名的文件解释php。

RemoveHandler .html
AddType application/x-httpd-php .php .html

现在,您可以使用简单的php脚本来包含其他文件,例如:

<?php include('b.html'); ?>

如果需要包含某些文件中的html内容,则可以使用以下代码:例如,以下行将在对象定义发生的位置包括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

这是我的就地解决方案:

(() => {
    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>

在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代码块b.htmla.html,这应该进入head的标签a.html

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

然后在body标签中,创建一个具有唯一ID和javascript块b.html的容器,以将其加载到容器中,如下所示:

<div id="b-placeholder">

</div>

<script>
$(function(){
  $("#b-placeholder").load("b.html");
});
</script>

我知道这是一个非常古老的帖子,因此当时还没有一些方法。但是,这是我非常简单的看法(基于Lolo的回答)。

它依赖于HTML5 data- *属性,因此非常通用,因为它使用jQuery的for-each函数来获取每个匹配“ load-html”的.class,并使用其各自的“ 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>

大多数解决方案都可以,但是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>

jQuery include github上的插件

您可以使用HTML导入的polyfill(https://www.html5rocks.com/en/tutorials/webcomponents/imports/),也可以使用简化的解决方案
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手动运行,获取日志等。请享用 :)

要插入命名文件的内容:

<!--#include virtual="filename.htm"-->

Athari的答案(第一个!)太定论了!很好!

但是,如果您希望将要包含的页面名称作为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>

对我来说效果很好!希望对您有所帮助:)

这是我使用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>

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策略阻止。由于深层网络的特性,可能需要访问深层网络才能使用它。(无实际用途)

暂时没有直接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并且可能会提出一个想法(我希望)

您可以使用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的原因,这并不是一种很好的方法。

您是否尝试过iFrame注入?

它将iFrame注入文档中并删除自身(应该在HTML DOM中被删除)

<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>

问候

这是一篇很棒的文章,您可以实现公共库,只需使用下面的代码一行即可导入任何HTML文件。

<head>
   <link rel="import" href="warnings.html">
</head>

您也可以尝试使用Google Polymer

使用ES6反引号 ``:模板文字

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);

https://caniuse.com/#feat=template-literals

将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>

... 希望能帮助到你。

我还有另一种解决方案

在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;
  });

Web组件

我创建类似于JSF的以下Web组件

<ui-include src="b.xhtml"><ui-include>

可以将其用作页面内的常规html标签(包括代码段js代码之后)

我来到此主题的目的是寻找类似的东西,但与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 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>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;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>
本文地址:http://javascript.askforanswer.com/zaihtmlwenjianzhongbaohanlingyigehtmlwenjian.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!