여러 페이지에서 탐색 모음을 재사용하려면 어떻게해야합니까?


83

방금 home / index.html 페이지 만들기를 마쳤습니다. 탐색 모음을 현재 위치에 유지하고 사용자가 모든 내 페이지를 클릭하는 동안 그대로 유지합니다. 탐색 코드를 각 페이지 상단에 복사하여 붙여 넣어야합니까? 아니면 더 깔끔하게 보이도록하는 다른 방법이 있습니까?

HMTL 탐색 :

<nav>
    <div>
        <a href="/">
            <div id="logo"><img src="image.png" alt="Home"/></div>
            <div id="headtag"><img src="image.png" alt="Home"/></div>
            <div id="tagline"><img src="image.png" alt="Home"/></div>
        </a>
    </div>
    <div> 
        <a href="/" class="here">Home</a>
        <a href="/about.html" >About</a>      
        <a href="/services.html" >Services</a>          
        <a href="/pricing.html" >Pricing</a>    
        <a href="/contact.html" >Contact Us</a>
        <input id="srchbar" type="search" placeholder="Search">
    </div>
</nav>

Yes. Keep in mind that when a user clicks a link in your navigation, your server/local system is sending the file indicated by the link to be downloaded and displayed. When they click "About," about.html will be loaded by the browser. So it should contain the same navigation.
Purag

1
if you have a server side language you can put this code in a template and include in all pages else use angular js to make this a directive
joyBlanks

3
I'm looking for the same thing. This is a shame that in 2017 we can't do this with a client based web site. Microsoft has had the concept of a master page (_layouts in the current version) forever. Seems like a client side "container page" wouldn't be ridiculous.
Ron

답변:


76

This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head tag:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html into the container, as follows:

<!--Navigation bar-->
<div id="nav-placeholder">

</div>

<script>
$(function(){
  $("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->

Hello. I don't know anything about jquery/javascript but I just wanted to try this. I tried doing exactly what you said. I have my nav menu on one page without any other tags and I included the rest of the code in the head/body of my index page (simple index page). However, it doesn't load my navbar on all pages. Any idea what I might do wrong ? Thank you !
Lay

@Lay does it show at all? I have to tell you that while development (loading the page locally) this code often does not work. Have you placed this code on a server?
Ramtin

3
Slightly off-topic, and forgive my ignorance: if you hardcode the jQuery version as you did in your answer: <script src="https://code.jquery.com/jquery-1.10.2.js"></script>, then what happens to your page when Version 1.10.3 or 1.11.0 come out?
Laryx Decidua

1
@LaryxDecidua Then it continues to work. Always loading the latest version would risk breaking the page. Think of breaking changes between versions. Therefore testing is recommended when switching to a different version.
Markus Pscheidt

1
I used the above code in index.html on local pc, tested in chrome, it give me error below and the nav.html not able to be loaded.jquery.min.js:4 Access to XMLHttpRequest at 'nav.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. Any idea?
KenyKeny

35

I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.

First, create a page with all the navigation bar's HTML content.

Next, use jQuery's $.get method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html and added a placeholder tag (Like <div id="nav-placeholder">) in your index.html, then you would use the following code:

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
    $("#nav-placeholder").replaceWith(data);
});
</script>

4

You can use php for making multi-page website.

  • Create a header.php in which you should put all your html code for menu's and social media etc
  • Insert header.php in your index.php using following code

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

(Above code will dump all html code before this)Your site body content.

  • Similarly you can create footer and other elements with ease. PHP built-in support html code in their extensions. So, better learn this easy fix.

1
So are you all saying i should convert all this to PHP, instead of multiple HTML pages for my site? It's my first site, and I know html, thats why I used it, but if it should be PHP, then it should be PHP.... So which should it be?
blackRob4953

This is very basic php which you can learn easily. You won't face nightmare's once when you convert your side to use a server side language. I do recommend this. But if you are intend to use only html, consider .shtml for small issues, still i find it clunky for growing websites.
Sachin Kanungo

Ok. Now that this page is html. How do i convert it to php? Is it a few entries or do I have to redo all my tags? And if so, how.... So I don't screw it up ha
blackRob4953

1
Change extension to .php and you're done. use following code braces to enter php code <?php include 'header.php'; ?> Go to php.net or w3schools for basic learning.
Sachin Kanungo

3

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).


3

Brando ZWZ provides some great answers to handling this situation.

Re: Same navbar on multiple pages Aug 21, 2018 10:13 AM|LINK

As far as I know, there are multiple solution.

For example:

The Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar).

Then we could directly load it from the jquery without writing a lot of codes.

Like this:

    <!--Navigation bar-->
    <div id="nav-placeholder">

    </div>

    <script>
    $(function(){
      $("#nav-placeholder").load("nav.html");
    });
    </script>
    <!--end of Navigation bar-->

Solution2:

You could use JavaScript code to generate the whole nav bar.

Like this:

Javascript code:

$(function () {
    var bar = '';
    bar += '<nav class="navbar navbar-default" role="navigation">';
    bar += '<div class="container-fluid">';
    bar += '<div>';
    bar += '<ul class="nav navbar-nav">';
    bar += '<li id="home"><a href="home.html">Home</a></li>';
    bar += '<li id="index"><a href="index.html">Index</a></li>';
    bar += '<li id="about"><a href="about.html">About</a></li>';
    bar += '</ul>';
    bar += '</div>';
    bar += '</div>';
    bar += '</nav>';

    $("#main-bar").html(bar);

    var id = getValueByName("id");
    $("#" + id).addClass("active");
});

function getValueByName(name) {
    var url = document.getElementById('nav-bar').getAttribute('src');
    var param = new Array();
    if (url.indexOf("?") != -1) {
        var source = url.split("?")[1];
        items = source.split("&");
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var parameters = item.split("=");
            if (parameters[0] == "id") {
                return parameters[1];
            }
        }
    }
}

Html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="main-bar"></div>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <%--add this line to generate the nav bar--%>
    <script src="../assets/js/nav-bar.js?id=index" id="nav-bar"></script>
</body>
</html>

https://forums.asp.net/t/2145711.aspx?Same+navbar+on+multiple+pages


-5

I don't know if it'll work for you but it works for me. Try to place the navigation codes without any header or body tag(just the code where the navigation bar started and ended). What will happen is you'll be placing separately the codes for the navigation bar. Let's say you already have the navigation codes on navigation.html and you'll include it to other page, let's say that would be index.php. To include it place inside the body tag and the navigation bar would be loaded on it.


2
It's not at all clear what you're suggesting here. Please provide markup samples.
isherwood

Soooooooo.... What you're answer is the same as the one @Ramtin posted? If so, I understand, but you need to add some clarity, or remove the answer altogether.
Momoro
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.