How To Make Reuseable HTML Navigation Menus?

前端 未结 10 828
面向向阳花
面向向阳花 2021-01-02 04:41

I\'m sure this topic comes up all the time,
But I can\'t seem to fine a concise answer.

I\'ve got a vertical menu bar that I want to reuse in webpages (>20)

10条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 05:42

    I've done this two separate ways - one using server side (PHP) and one using Javascript includes (for demos that need to be able to run without any internet connection or server capabilities).

    For PHP includes your pages will have to end with .php rather than .htm or .html, and these are very ideal to replace your header, footer, navigation, etc. Anything that is repeated on multiple pages.

    Basically you would create your normal code then copy and paste the code you want to break out - in this example, your navigation - and save it in another file called (for example) inc_navigation.htm (this page can be called .htm).

    Then in your actual pages you'd use the following code:

    
    

    That would insert your navigation at that point, if you had a change to make you'd make it to the .htm file and it would propagate to any page with that included.

    For javascript includes you will have to include the following line at the top of every document where you want to include your navigation:

    
    

    Then you'll create a document called includes.js.

    At the top of this document you'll declare your navigation variable:

    var navigation  = new Array();  // This is for the navigation.
    

    Then a little ways down in that same document you need to actually outline your navigation code (the line numbers in the square brackets are crucial - keep them in order and start with 0 - you cannot have line breaks in this code so every line of code has to be a new line):

    // ==================== Navigation ==================== //
    navigation[0]   = '
    '; navigation[1] = '
      '; navigation[2] = '
    • Home
    • '; navigation[3] = '
    • About Us
    • '; navigation[4] = '
    '; navigation[5] = '
    ';

    Then a little ways after that you'll actually insert the javascript that will put that code into your page (it doesn't actually put it there but rather makes it accessible in the page without actually altering the code of the .htm page - so if you view source you'll see the reference to the code not the code itself).

    function show(i)
     {
      for (x in i)
      {
       document.write(i[x]+'\n')
      }
     }
    

    Finally - in your .htm document, say for your index.htm page, you'll replace your navigation code (that you put in the above block called navigation) with this:

    
    

    Where that name after SHOW and in the parenthesis is the name of your variable (declared earlier).

    I have sites showing both methods in use if you'd like to see them just send me a message.

提交回复
热议问题