简体   繁体   中英

Pages load in div, don't want to make a new page for home page

I use jQuery to load new pages inside of a div, but I don't want to make a page just for the content I have in that div on my home page. My script is as follows:

<script type="text/javascript">
    $(document).ready(function() {
        $(".navigation").on("click", function(){  
            $("#content").load($(this).attr("page"));
            return false;
        });
    });
</script>

Everything loads fine in

<div id="content"></div>

but my navigation section is structured to have HOME be a selection.

<nav id="menu">
    <a href="" title="" page="home.php" class="navigation">Home</a>
    <a href="" title="" page="about.php" class="navigation">About</a>
</nav>

So is there a way to get the script to load whatever I have inside of the "content" div in my original page, or would it just be easier to make the "HOME" button be an actual link to the index page?

Everything still works if I change it to

<a href="index.php" title="">Home</a>

I just don't like the whole page loading as opposed to clicking on other buttons on the site and only having the content load.

From the jQuery docs :

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

So you can do something like this:

<script type="text/javascript">
    $(document).ready(function() {
        $(".navigation").on("click", function(){  
            var page = $(this).data("page");
            if(page == "index.php"){                    
                 //Load only element with id content from index.php
                 $("#content").load(page + " #content"); 
            } else{
                $("#content").load(page);
            }
            return false;
        });
    });
</script>

<nav id="menu">
    <a href="" title="" data-page="index.php" class="navigation">Home</a>
    <a href="" title="" data-page="about.php" class="navigation">About</a>
</nav>

PS. You shouldn't use invalid attributes as pointed out by adeneo, so I changed yours to data attributes.

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