简体   繁体   中英

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

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. Then you can compile those pages and generate HTML output rendering the full page.

Checkout 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's include feature allows you to do exactly what you want to do. ( https://pugjs.org/language/includes.html )

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM