简体   繁体   中英

Click a button and it should load the content into the main content area

I have create 3 buttons on the left menu for "Cars," "Music," and "Games" When the user clicks one, it should load the appropriate contents into a DIV in the main content area. Each button should replace the contents of anything previously displayed in the div. I created my buttons, but I do not know how to load the content into the main content div or how to replace the previous content. Can you help please?

使用jQuery 加载功能

<!DOCTYPE HTML>
<html>
<head>
<title>Title of the document</title>
<script src="../js/jquery.js"></script>  
<script>
    function load(url){
        $('#content').load(url);
    }
</script>
</head>

<body>  
  <button onclick='load("url1");'>Content 1</button>
  <button onclick='load("url2");'>Content 2</button>

  <div id='content'></div>
</body>

UPDATE Ok lets clarify it a bit.

The code above uses jQuery lib. Look here for more info about load function.

If you cannot or dont want to use jQuery look here for JS solution.

If you want to use only static content then you have two another options:

//1: if the new content is only small portion of info text
<script>
  function load(newContent){
     document.getElementById('content').innerHTML = newContent;
  }
</script>
<button onclick='load("some text 1");'>Content1</button>
<button onclick='load("another text 2");'>Content2</button>

<div id='content'></div>

//2: put content directly to your page the several DIVs and hide them
<script>
  function show(index){
     var n=2; // number of DIVs

     //show desired content and hide any others   
     for(var i=1; i<=n; i++){
        document.getElementById('content'+i).style.display = i == index ? 'block' : 'none';
     }
  }
</script>

<button onclick='show(1);'>Content 1</button>
<button onclick='show(2);'>Content 2</button>

<div id='content1'></div>
<div id='content2' style='display:none;'></div>

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