简体   繁体   中英

Single navigation bar across website?

I am currently building a web application for my employer, but I have some restrictions. It has to be in HTML, CSS, and Javascript for the front end, and I have to use a lot of different pages for this, each sharing the same navigation bar.

If the navigation is the same for each page, is it possible to write the navigation bar once and use it across the entire website? I am just annoyed when I make a change to a link or something and I have to run through and change each pages respective navigation link. Normally I'd use something like Angular to achieve this, but I am not sure how to do it with this more barebones approach. They really don't use any JS libraries either so if there's a way to do it with "raw" HTML CSS and JS I'd love to learn how this works if it exists.

JQuery

As JQuery is JS-based, you might be allowed to use it. You could then add a navigation div into each page's template:

<div id="navigation"></div>

and include a script on each page that executes the following JQuery-code:

$(function() {
    $("#navigation").load("navigation.html");
});

Pure JavaScript

Alternatively, if you cannot use JQuery whatsoever, you could use plain JavaScript, which is more lightweight but not as clean.

Wherever you want to include the navigation, simply include a script:

<script src="nav.js"></script>

Which holds your navigation based on document.write :

document.write('<div>\
    ... your navigation content ...\
    </div>\
');

The easiest way would just be to write the code in a JS file, and include that code on your pages. You can hard code it or make it more intelligent, but here's a basic demo.

 var html = '<ul>\\ <li>\\ <a href="#">link</a>\\ </li>\\ <li>\\ <a href="#">link</a>\\ </li>\\ <li>\\ <a href="#">link</a>\\ </li>\\ </ul>'; document.getElementById('nav').innerHTML = html;
 <nav id="nav"></nav>

You can include html files inside html with the w3 library.

<div w3-include-html="navbar.html"></div>

<script>
    w3.includeHTML();
</script>

Check out this w3schools link .

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