开发者

Coding a Menubar in one place only

I'm designing a website for a law office. Each page will have the same basic layout as you see here: The same title bar, the same menu bar on the left, and the same footer. Th开发者_运维知识库e only thing that will change from page to page is the content section.

My first approach would be to duplicate the code for these common elements for each content page. Then, in the future, if things need to be changed on those bars (certainly going to happen), I would have to go into each and every sub page to make the changes.

This makes the programmer in me shudder. I have to imagine there is a way do to this without using a crazy html-programming suite. (I'm using notepad++ right now to code). Is there a way to write the html code for the menu bar in one place and then "source" it in, like I do with the javascript and css code?

I know something like this can be done with frames, but I don't want to go that route.


If you can use some PHP, it will make your life easier. Just a look on inlude() function, this is really what you are looking for.

You'll have a file for footer, one for header, one for the menu, and then, in you page, you can just use :

<?php include('header.php'); ?>

<?php include('menu.php'); ?>

<!-- Your content somewhere here -->

<?php include('footer.php'); ?>


If you are restricted to using only HTML/JS for some reason, you can use jQuery's load() method:

$('#menu').load('includes/menu.html');

This will load the HTML from menu.html and place it within the #menu element. However, if possible, go with something similar to what Haza suggests.


If you don't want to mess with server stuff, you could create a javascript function that creates the HTML for you and then writes it to the page. For instance

function writeNavigation(){
document.write("<nav>");
document.write("  <li> home <\/li>");
document.write("  <li> about <\/li>");
document.write("  <li> blog <\/li>");
document.write("</nav>");
}

This way, you could link to the file in the head of your HTML page like this ->

And then, you could simply call the function when the page loads like this ->

<script type='text/javascript'>
window.onload = writeNavigation()
</script>

However, using this has no fallback method, so users without JavaScript will be left with no menu.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜