HTML 파일에 다른 HTML 파일 포함
두 개의 HTML 파일이 있다고 가정 a.html
하고 b.html
. 에 a.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 중 하나와 유사합니다 . 그러나 jQuery를 사용하는 대신 JavaScript의 document.write를 통해 HTML 코드를 삽입합니다.
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
크레딧 그렉 Minshall 내 원래 나오지도 명령은 고려하지 않았다 또한 다시 슬래시와 따옴표를 이스케이프 개선 나오지 명령합니다.
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" -->
아주 오래된 솔루션은 나는 다시 내 요구를 충족하지만, 여기에 표준을 준수하는 코드를 수행하는 방법 않았다
<!--[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]-->
스크립트가 필요 없습니다. 서버 측에서 멋진 일을 할 필요가 없습니다 (아마 더 나은 옵션이 될 것입니다)
<iframe src="/path/to/file.html" seamless></iframe>
오래된 브라우저는 매끄럽지 못하므로 CSS를 추가하여 수정해야합니다.
iframe[seamless] {
border: none;
}
매끄럽지 않은 브라우저의 경우 iframe에서 링크를 클릭하면 프레임 이 전체 창이 아닌 해당 URL로 이동합니다. 이를 우회하는 방법은 모든 링크가있는 것입니다 target="_parent"
. 따라서 브라우저 지원이 "충분히 양호"합니다.
대안으로 서버의 .htaccess 파일에 액세스 할 수있는 경우 .html 확장자로 끝나는 파일에서 php를 해석 할 수있는 간단한 지시문을 추가 할 수 있습니다.
RemoveHandler .html
AddType application/x-httpd-php .php .html
이제 간단한 PHP 스크립트를 사용하여 다음과 같은 다른 파일을 포함 할 수 있습니다.
<?php include('b.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
이것이 나를 도왔습니다. 에서 HTML 코드 블록을 추가하려면 b.html
에 a.html
이은에 가야 head
의 태그 a.html
:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
그런 다음 body 태그에서 b.html
다음과 같이 컨테이너에 를로드하기 위해 고유 ID와 자바 스크립트 블록으로 컨테이너를 만듭니다.
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
HTML 가져 오기의 폴리 필 ( 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" >
임포터는 SSI와 매우 유사한로드 된 HTML로 지시문을 대체합니다.
이 지시문은이 작은 자바 스크립트를로드하는 즉시 자동으로 제공됩니다.
<script async src="./src/html-import.js"></script>
DOM이 자동으로 준비되면 가져 오기를 처리합니다. 또한 수동으로 실행하거나 로그를 가져 오는 데 사용할 수있는 API를 제공합니다. 즐겨 :)
나는 이것이 매우 오래된 게시물이라는 것을 알고 있으므로 그 당시에는 일부 방법을 사용할 수 없었습니다. 그러나 여기에 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>
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를 참조하십시오.
명명 된 파일의 내용을 삽입하려면 :
<!--#include virtual="filename.htm"-->
Athari의 대답 (첫 번째!)은 너무 결정적이었습니다! 아주 좋아요!
그러나 URL 매개 변수로 포함 할 페이지의 이름 을 전달하려면 이 게시물과 함께 사용할 수있는 매우 좋은 솔루션이 있습니다.
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
따라서 다음과 같이됩니다.
귀하의 URL :
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>
그것은 나를 위해 아주 잘 작동했습니다! 나는 도움이 되었기를 바랍니다 :)
대부분의 솔루션은 작동하지만 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>
html5rocks.com 은 이것에 대한 아주 좋은 튜토리얼을 가지고 있으며, 이것은 조금 늦을 수도 있지만, 이것이 존재한다는 것을 저도 몰랐습니다. w3schools에는 w3.js라는 새로운 라이브러리를 사용하여이를 수행하는 방법도 있습니다. 문제는 웹 서버와 HTTPRequest 객체를 사용해야한다는 것입니다. 실제로 로컬로로드하고 컴퓨터에서 테스트 할 수는 없습니다. 그래도 할 수있는 것은 상단의 html5rocks 링크에 제공된 폴리 필을 사용하거나 튜토리얼을 따르는 것입니다. 약간의 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 (영구적 으로 draft에 있음 ) 조차도 작업을 수행하지 않습니다. 왜냐하면 Import! = Include 및 일부 JS 마법이 어쨌든 필요하기 때문입니다.
저는 최근에 복잡한 문제없이 HTML을 HTML에 포함하기위한 VanillaJS 스크립트 를 작성 했습니다 .
당신의 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
과 아이디어를 (I 희망) 제공 할 수 있습니다
다음과 같이 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상의 이유로 좋은 방법이 아닙니다.
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>
여기에 훌륭한 기사가 있습니다. 공용 라이브러리를 구현하고 아래 코드를 사용하여 HTML 파일을 한 줄로 가져올 수 있습니다.
<head>
<link rel="import" href="warnings.html">
</head>
Google Polymer를 사용해 볼 수도 있습니다.
나는 비슷한 것을 찾기 위해이 주제에 왔지만 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>
PHP는 서버 수준 스크립팅 언어입니다. 많은 일을 할 수 있지만 널리 사용되는 용도 중 하나는 SSI와 마찬가지로 페이지 내에 HTML 문서를 포함하는 것입니다. SSI와 마찬가지로 이것은 서버 수준의 기술입니다. 웹 사이트에 PHP 기능이 있는지 확실하지 않은 경우 호스팅 제공 업체에 문의하십시오.
다음은 PHP 지원 웹 페이지에 HTML 스 니펫을 포함하는 데 사용할 수있는 간단한 PHP 스크립트입니다.
사이트의 공통 요소에 대한 HTML을 별도의 파일에 저장하십시오. 예를 들어 내비게이션 섹션은 navigation.html 또는 navigation.php로 저장 될 수 있습니다. 다음 PHP 코드를 사용하여 각 페이지에 해당 HTML을 포함합니다.
<?php require($DOCUMENT_ROOT . "navigation.php"); ?>
파일을 포함하려는 모든 페이지에서 동일한 코드를 사용하십시오. 강조 표시된 파일 이름을 포함 파일의 이름과 경로로 변경해야합니다.
django / bootle과 같은 프레임 워크를 사용하는 경우 종종 템플릿 엔진을 제공합니다. bottle을 사용하고 기본 템플릿 엔진이 SimpleTemplate Engine 이라고 가정 해 보겠습니다 . 그리고 아래는 순수한 html 파일입니다.
$ cat footer.tpl
<hr> <footer> <p>© stackoverflow, inc 2015</p> </footer>
다음과 같이 기본 파일에 footer.tpl을 포함 할 수 있습니다.
$ cat dashboard.tpl
%include footer
그 외에도 dashborard.tpl에 매개 변수를 전달할 수도 있습니다.
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에 포함
바꾸기-> div를 바꿉니다.
동일한 디자인에 따라 더 많은 동작을 쉽게 추가 할 수 있습니다.
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
Promise와 함께 Fetch API를 사용하는 또 다른 접근 방식
<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>
위의 모든 솔루션에는 JS가 새로 포함 된 HTML을 대상으로하는 이벤트 후크가 없습니다. 또한 많은 사람들이 브라우저 호환성이 좋지 않았습니다.
그래서 간단한 HTML include 스크립트에 비해이 두 가지 장점이 필요한 사람을 위해 라이브러리를 만들었습니다.
다음은 JS 라이브러리입니다. includeme.js
솔루션이 작동하려면 여기에서 찾을 수있는 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>
... 도움이되기를 바랍니다.
참고 URL : https://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file
'development' 카테고리의 다른 글
What characters are allowed in an email address? (0) | 2020.10.03 |
---|---|
자바 스크립트에서 배열을 복제하는 가장 빠른 방법-슬라이스 대 'for'루프 (0) | 2020.10.03 |
JavaScript에서 문자열을 날짜로 변환 (0) | 2020.10.03 |
확인되지 않은 캐스트 경고는 어떻게 해결합니까? (0) | 2020.10.03 |
한 AngularJS 컨트롤러가 다른 컨트롤러를 호출 할 수 있습니까? (0) | 2020.10.03 |