머리글 및 바닥글 파일을 여러 html 페이지에 포함시킵니다.
여러 html 페이지에 포함된 공통 머리글 및 바닥글 페이지를 만들고 싶습니다.
자바스크립트를 사용하고 싶습니다.html과 자바스크립트만 사용해서 이것을 할 수 있는 방법이 있습니까?
다른 html 페이지 내에서 머리글과 바닥글 페이지를 로드하고 싶습니다.
jquery를 사용하면 이 작업을 수행할 수 있습니다.
를 이코배 위치치에 합니다.index.html
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
그리고 이 코드를 넣으십시오.header.html그리고.footer.html 같은 에서.index.html
<a href="http://www.google.com">click here for google</a>
자, 당신이 방문할 때index.html링크 태그를 클릭할 수 있어야 합니다.
서버 사이드 포함을 사용하여 공통 부분을 머리글 및 바닥글로 추가합니다.HTML 및 JavaScript가 필요하지 않습니다.대신 웹 서버는 다른 작업을 수행하기 전에 포함된 코드를 자동으로 추가합니다.
파일을 포함할 위치에 다음 행을 추가하기만 하면 됩니다.
<!--#include file="include_head.html" -->
자바스크립트와 함께 html 파일 구조를 사용해야 합니까?당신은 간단한 PHP 인크루드 오브젝트를 사용할 수 있도록 대신 PHP를 사용하는 것을 고려해 본 적이 있습니까?
.html 페이지의 파일 이름을 .php로 변환하면 각 .php 페이지의 맨 위에 한 줄의 코드를 사용하여 헤더의 내용을 포함할 수 있습니다.
<?php include('header.php'); ?>
각 페이지의 바닥글에서 동일한 작업을 수행하여 바닥글의 내용을 포함합니다.php 파일
<?php include('footer.php'); ?>
JavaScript/Jquery 또는 추가 포함 파일이 필요하지 않습니다.
NB 또한 .htaccess 파일에서 다음을 사용하여 .html 파일을 .php 파일로 변환할 수 있습니다.
# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
다음과 같이 입력할 수도 있습니다. (load_essentials.js:)
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you@you.com'>Contact Us</a> / "
+ "<a href='mailto:you@you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
HTML과 JavaScript만 사용하는 것에 대한 질문입니다.문제는 자바스크립트 또는 심지어 jQuery를 사용하여 서버에 대한 두 번째 요청(추가 요청)입니다.header.html"나중에")는 다음과 같습니다.
천천히!
따라서 프로덕션 환경에서는 이를 허용할 수 없습니다.의 은하포것입다니는함하나만방법▁only▁one다▁the것니입▁to를 포함하는 것입니다..js이 .js 파일만 사용하여 HTML 템플릿을 파일로 저장하고 제공합니다.1단계에서는 HTML에서 다음을 수행할 수 있습니다.
<header id="app-header"></header>
<script async src="header.js"></script>
, 의 그단다 2계서템저장다니합을에 .header.js다음 문자열에 합니다: html 자에스백사용:
let appHeader = `
<nav>
/*navigation or other html content here*/
</nav>
`;
document.getElementById("app-header").innerHTML = appHeader;
이것은 또한 자바스크립트이기 때문에 필요할 때 템플릿의 내용을 동적으로 변경할 수 있다는 이점이 있습니다!또한, 시도해보세요.defer비동기 대신(또는 아무것도 없음), 그러나 사용자에게는 더 느리게 보일 수 있습니다. 이것은 사용자의 다른 콘텐츠에 따라 다르므로 시도해 보십시오.그냥, 잊지 말고 그것을.script에 header.
속도에 대한 설명
/2와 파일 .을 "..html초기 응답에서 모두 전송합니다.하지만, 만약 당신의 "원본"에 있다면,.html당신은 이것을 가지고 있지 않습니다.header.html가져온 파일(나중에 스크립트로 호출할 예정이므로)은 처음에 전송되지 않습니다.따라서 JavaScript/jQuery가 요청할 때(HTML 및 JavaScript가 "해석"될 때 훨씬 나중에 발생) 브라우저는 서버에 두 번째 요청을 보내고 응답을 기다린 다음 작업을 수행합니다.그래서 이게 느린 거예요.브라우저의 개발자 도구를 사용하여 이 기능을 검증할 수 있습니다.header.html훨씬 뒤에 오는
인 조언으로 원래의 모든 ..html(또는)php) 속도가 신경 쓰이는 경우 파일을 사용합니다.defer또는async필요한 경우에는나중에 JavaScript를 사용하여 파일을 가져오지 마십시오.
저는 이것을 시도했습니다: 파일 헤더를 만듭니다. html과 같이.
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
이제 HTML 페이지에 header.html을 다음과 같이 포함합니다.
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
완벽하게 잘 작동합니다.
저는 C#/Razor에서 일을 해왔고 제 집 노트북에 IIS가 설정되어 있지 않기 때문에 우리 프로젝트를 위한 정적 마크업을 만드는 동안 뷰에 로드할 자바스크립트 솔루션을 찾았습니다.
"ditching jquery" 방법을 설명하는 웹 사이트를 우연히 발견했는데, 사이트의 방법이 일반 Jane Javascript(게시물 하단의 참조 링크)에서 정확히 원하는 것을 수행한다는 것을 보여줍니다.운영 환경에서 이 기능을 사용하려는 경우 보안 취약성 및 호환성 문제를 조사해야 합니다.저는 그렇지 않아요, 그래서 제가 직접 조사해 본 적이 없어요.
JS 함수
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
내용 가져오기
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
색인.
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
견해/의견
<!-- This element will replace #header -->
<header id="new-header"></header>
출처는 제 것이 아니라 OP에 대한 좋은 바닐라 자바스크립트 솔루션이기 때문에 참고하는 것입니다.원본 코드는 http://gomakethings.com/ditching-jquery#get-html-from-another-page 에 있습니다.
이 질문에 대한 답은 너무 오래된 것 같아요현재 일부 데스크톱 및 모바일 브라우저는 이 작업을 위해 HTML 템플릿을 지원합니다.
저는 작은 예시를 만들었습니다.
Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 및 Adblocker Browser 54.0에서 정상 테스트됨
Safari 10.1, Firefox 56.0, Edge 38.14 및 IE 11에서 KO 테스트 완료
더 많은 호환성 정보는 canisue.com 에서 확인할 수 있습니다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
당신은 이 HTML5 Rocks 게시물에서 더 많은 예를 얻을 수 있습니다.
2018년 알로하.안타깝게도, 저는 여러분과 공유할 멋지고 미래적인 것이 없습니다.
하지만 저는 jQuery를 언급한 사람들에게 지적하고 싶습니다.load()메소드가 현재 작동하지 않습니다. 아마도 로컬 웹 서버를 실행하지 않고 로컬 파일에 메소드를 사용하려고 할 것입니다.언급한 "origin" 오류가 합니다. 이이 "cross origin"과 같은 합니다.http,data또는https을 하지 않는 것으로 (header.html 파일은 사용자가 요청하는 페이지에 .)
따라서 위에서 수락한 답변이 사용자에게 적합하지 않은 경우 웹 서버를 실행하고 있는지 확인하십시오.서두르는 경우(그리고 Python이 미리 설치된 Mac을 사용하는 경우) 가장 빠르고 간단한 방법은 간단한 Python http 서버를 회전시키는 것입니다.여러분은 여기서 그것을 하는 것이 얼마나 쉬운지 알 수 있습니다.
이것이 도움이 되길 바랍니다!
하지 않았기 에 일반자크트사빠설른위정아그응해을, 다때또수있니습사할용한당에문신은바않을 할 수도 ..js변수 안에 HTML의 중복 조각(템플릿)을 저장하고 삽입하기 위한 파일innerHTML.
백트릭은 여기에 있습니다. 쉬운 부분은 이 답에 관한 것입니다.
(답안을 읽고 테스트할 경우에는 역기입 SOQ/A에 있는 링크를 따라가기도 합니다.)
각 페이지에서 동일하게 유지되는 탐색 모음의 예:
<nav role="navigation">
<a href="/" class="here"><img src="image.png" alt="Home"/></a>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
</nav>
HTML 내부에 보관할 수 있습니다.
<nav role="navigation"></nav>
그리고 파일 안에 내용을 설정합니다.<nav>백스틱 사이의 변수로:
const nav= `
<a href="/" class="here"><img src="image.png" alt="Home"/></a>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
` ;
HTML을 포함하는 변수를 검색할 수 있는 작은 파일이 있습니다. 포함하는 것과 매우 유사합니다.php 그리고 그것을 망치지 않고 쉽게 업데이트할 수 있습니다 (백스틱 안에 있는 것).
자바스크립트 로 내부 자바스크립트 파일과 할 수 .HTML the varnav東京의 <nav role="navigation"></nav>경유로
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
, 한 .nav.js
기본 HTML 페이지는 다음과 같습니다.
// code standing inside nav.js for easy edit
const nav = `
<a href="/" class="here"><img src="image.png" alt="Home"/></a>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
`;
nav[role="navigation"] {
display: flex;
justify-content: space-around;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<!-- update title if not home page -->
<meta name="description" content=" HTML5 ">
<meta name="author" content="MasterOfMyComputer">
<script src="nav.js"></script>
<!-- load an html template through a variable -->
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<nav role="navigation">
<!-- it will be loaded here -->
</nav>
<h1>Home</h1>
<!-- update h1 if not home page -->
<script>
// this part can also be part of nav.js
window.addEventListener('DOMContentLoaded', () => {
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
});
</script>
</body>
</html>
이 빠른 예제는 복사/붙여넣기 작업을 수행한 다음 변수 이름과 변수 HTML 내용을 변경할 수 있습니다.
헤더에 스크립트와 링크를 로드할 수도 있습니다.위의 예시 중 하나를 추가하겠습니다.
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you@you.com'>Contact Us</a> / "
+ "<a href='mailto:you@you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
이 질문이 처음 제기된 이후로 사용할 수 있는 또 다른 접근 방식은 reactrb-proxy를 사용하는 것입니다(http://reactrb.org 참조). 이렇게 하면 클라이언트 쪽에서 스크립트를 작성하여 html 코드를 루비로 작성된 react 구성 요소로 바꿀 수 있습니다.
아약스 사용
.js
fetch("./includes/header.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./includes/footer.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
색인.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Liks</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header></header>
<main></main>
<footer></footer>
<script src="/js/main.js"></script>
</body>
</html>
자바스크립트를 사용하지 않고 HTML의 객체 태그를 사용할 수 있습니다.
<object data="header.html" type="text/html" height="auto"></object>
포함할 HTML을 .html 파일에 저장합니다.
Content.html
<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>
HTML 포함
HTML을 포함하려면 w3-include-html 속성을 사용합니다.
예
<div w3-include-html="content.html"></div>
JavaScript 추가
HTML 포함은 JavaScript에 의해 수행됩니다.
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
통화 내용 포함페이지 하단의 HTML():
예
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>
언급URL : https://stackoverflow.com/questions/18712338/make-header-and-footer-files-to-be-included-in-multiple-html-pages
'programing' 카테고리의 다른 글
| 컨테이너의 로그가 포함된 로그 파일은 어디에 있습니까? (0) | 2023.08.25 |
|---|---|
| Excel 2016에서 CSV 파일 열기 (0) | 2023.08.25 |
| C# on load 이벤트에서 div 태그 내에 HTML을 동적으로 추가할 수 있습니까? (0) | 2023.08.25 |
| Node.js에서 next()를 사용하고 next()를 반환할 때 (0) | 2023.08.25 |
| iPhone 키보드 위에 도구 모음을 프로그래밍 방식으로 정렬 (0) | 2023.08.25 |