[英]how can i include part of a file in another file with javascript
I am creating a website and i dont intend to add a backend language.我正在创建一个网站,我不打算添加后端语言。 But i have a fixed header and navigation buttons which i want to include on other pages like the "about us" and "contact us" page.
但是我有一个固定的标题和导航按钮,我想将它们包含在其他页面上,例如“关于我们”和“联系我们”页面。 I have a single javascript file which is linked across all html pages.
我有一个链接到所有 html 页面的 javascript 文件。 I tried the following code but it didnt work.
我尝试了以下代码,但没有用。 Any help would be highly appreciated.
任何帮助将不胜感激。
function showHeader(){
var showHead = document.querySelector(".header-content");
document.querySelector("body").innerHtml = showHead;
}
<!--first html file-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>TITLE</title>
</head>
<body>
<div class="container">
<span class="header-content">
<a class="brand-name" href="index.html">
BRAND NAME
</a>
<span class="head-content-2">
<a class="navbar-link link1" href="index.html">Home</a>
<a class="navbar-link link2" href="about.html">AboutUs</a>
<a class="navbar-link link3" href="contact.html">Contact Us</a>
</span>
</span>
<!--second html file-->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>ABOUT US</title>
</head>
<body onload="showHeader()">
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
The javascript function that you added on second html file
won't work because below code line in the ShowHeader
function is looking for the DOM element which is not present on that page.您在
second html file
添加的 javascript 函数将不起作用,因为ShowHeader
函数中的代码行下方正在查找该页面上不存在的 DOM 元素。
var showHead = document.querySelector(".header-content");
I suppose you are looking for some HTML pre-processor so that you can write the common elements once and include it on any pages you want.我想您正在寻找一些 HTML 预处理器,以便您可以编写一次公共元素并将其包含在您想要的任何页面上。 Then you can compile those pages and generate HTML output rendering the full page.
然后您可以编译这些页面并生成呈现整个页面的 HTML 输出。
Checkout PUG ( https://pugjs.org/ ).结帐 PUG ( https://pugjs.org/ )。
Here is the link to useful article that will help you get setup and running with pug templates: https://codeburst.io/getting-started-with-pug-template-engine-e49cfa291e33这是有用文章的链接,可帮助您使用 pug 模板进行设置和运行: https : //codeburst.io/getting-started-with-pug-template-engine-e49cfa291e33
PUG's include feature allows you to do exactly what you want to do. PUG 的包含功能允许您做您想做的事情。 ( https://pugjs.org/language/includes.html )
( https://pugjs.org/language/includes.html )
I hope this helps!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.