开发者

Load and unload a page into a div from a navigation button

开发者 https://www.devze.com 2023-01-31 03:40 出处:网络
Can anyone 开发者_JAVA技巧tell me in the simplest code possible, how to load and unload an html page into a div named \"myDiv\", with a simple click?

Can anyone 开发者_JAVA技巧tell me in the simplest code possible, how to load and unload an html page into a div named "myDiv", with a simple click?

When i press another button on my navigation menu, i will then unload "myDiv" and replace with another page.

Whats the setup for this?

edit

I have 3 pages (page1.html, page2.html, page3.html)

My navigation is as follows:

<ul>
  <li><a href="page1.html"></a></li>
  <li><a href="page2.html"></a></li>
  <li><a href="page3.html"></a></li>
</ul>

I am trying to load those pages into "myDiv", each page replacing the previous loaded page everytime i click a different page button. Thats all.

I hope i made what im trying to do clear as crystal and hopefully not leaving anything important out.


Assuming you can use javascript/jQuery (you don't give a lot of info on your environment)...

Have a look at the jQuery load() method.

http://api.jquery.com/load/

<div id="myDiv"></div>
<button id="myButton">Click Me</button>

<script type="text/javascript">
    $( document ).ready( function() {
        $( '#myButton' ).click( function() {
            $( '#myDiv' ).load( 'test.html' );
        });
    });
</script>

That should do your load. I'll leave the rest to you :)

EDIT:

OK, something more along the lines of what you're looking for...

Assuming you can modify the markup and add a class attribute to your a elements...

<ul>
    <li><a href="page1.html" class="dynamicLoad"></a></li>
    <li><a href="page2.html" class="dynamicLoad"></a></li>
    <li><a href="page3.html" class="dynamicLoad"></a></li>
</ul>

<script type="text/javascript">
    $( document ).ready( function() {
        $( 'a.dynamicLoad' ).click( function( e ) {
            e.preventDefault();   // prevent the browser from following the link
            e.stopPropagation();  // prevent the browser from following the link

            $( '#myDiv' ).load( $( this ).attr( 'href' ) );
        });
    });
</script>

So any 'a' element with the class of dynamicLoad will trigger this when clicked. We don't want the browser to try and follow the link, so we use preventDefault() and stopPropagation(). The only other difference is that we're not statically loading "test.html". We're determining what html page to load by using jQuery's $( this ), which represents the element that triggered the function. Use the attr() method, which returns the value of a specific attribute of the element. In this case, the href attribute.

Questions?

0

精彩评论

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