简体   繁体   中英

Change div content with link in another div

i have a menu bar with links which are in the header. when you click the link, i want to just change the content in the main div. i'm thinking of doing it in php, but you will have to reload the page. So i need to do it in javascript, but i dont know javascript.

here is my menu code in the header div:

<ul id="nav">
    <li><a href="#">Enter Information</a></li>
    <li><a href="#">View Records</a></li>
    <li><a href="#">View Upcoming</a></li>
</ul>

Depending on the type of content, you have a few options available to you. If you need to load a new page into the main content, you can use iframes and some javascript. If you need to load simple text, you can simply use javascript.

Based on your feedback, you'll do something like this (note- I'm shooting from the hip regarding syntax, but this is generally what your code will need to look like):

<a href="#" onclick="UpdateIFrame('mypage.html')">Link 1</a>

<iframe id="MainContent">
</iframe>

<script>
   function UpdateIFrame( newPageAddress ){
     document.getElementById("MainContent").contentWindow.location = newPageAddress;
   }
</script>

If you think about using PHP, I guess that you have to load dynamic content. For this, I advice you to use AJAX

The easiest is to use a framework, like the famous Jquery. Example here

You don't need any anchor elements. W3 example

<script>
$(document).ready(function() {
    $('.menu').click(function() {
            $("div").load('somecontent.txt');       
    });
});
</script>

<ul>
    <li class="menu">Enter Information</li>
    <li class="menu">View Records</li>
    <li class="menu">View Upcoming</li>
</ul>

here i am assuming that you get your content with a function call as content()

var list=document.getElementById('nav');
var links=list.getElementsByTagName('a');
var header=document.getElementById('header');
for (var i=0;i<links.length;i++)
{
links[i].onclick=function() {
header.innerHTML=content();       //here you can use something else to generate the content
}
}

In order to dynamicly load content (eg from a server using php/sql) without having to reload the website Ajax is exactly what you need.

Inlineframes (mentioned before), however, should not be used for they are deprecated.

W3schools provides a very basic but straightforward tutorial on Ajax.

You want to use jquery to build something like this. If you are serious about building web apps you need to learn how to use it (or a similiar framework like MooTools )

For this particular problem I would use an existing menuing system, here's the first list of jquery based menus that I found, but there are many more.

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