简体   繁体   中英

HTML + jquery - menu to change contents in the content DIV

I've been digging around on how to do it, but didn't find any solution which would fulfill my needs.

Got a basic layout of my page with menu on the left, separate div for header and a div in the middle where all the content should be displayed when one of the menu buttons is selected.

I'd like to change the content only of the "content" div dynamically without reloading the page when one of the menu buttons is pressed.

I've managed to do it as per below with jquery:

        <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){

            $('#nav ul li a').click(function(){
                $('#main').load('contents.html #' + $(this).attr('href'));
                return false;
            });

        });

The menu :

        <nav id="nav">
            <ul class="menu">
                <li class="menu1"><a href="menu1"></a></li>
                <li class="menu2"><a href="menu2"></a></li>
                <li class="menu3"><a href="menu3"></a></li>
                <li class="menu4"><a href="menu4"></a></li>
                <li class="menu5"><a href="menu5"></a></li>
            </ul>
        </div>
    </nav>  

contents.html file sample:

<div id="menu1">
    <h2>Menu1</h2>
    <p>Menu1 page contents</p>
</div>

So when menu1 button is pressed I'm able to change the content of main div to reflect the relevant data - this works.

My questions are:

1) is this the correct way on how to do it ? If not what would you recommend ?

2)I want to display more advanced stuff not only text (eg What if I want to have another jquery in the div-id="menu1" ? I've tried it and it didn't work.)

PS - I'm just a beginner so maybe I've missed something basic - but couldn't fix it by myself.

Thanks in advance!

Peter

I think there are a number of ways to achieve what you want. It depends on the nature of the content you want to load.

If there isn't masses of it, you could load it all onto the page on page load within different div's and then just show and hide the relevant div when clicking the menu items. (have a look at twitter bootstrap for some implementations, things like tabbed browsing).

If you do just have text, you could use ajax to load in the data from an external file w3schools.com .

Alternatively as mentioned in a comment above, you could create a single page application using something like angular.js , knockout.js etc.

Hope that helps.

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