开发者

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

开发者 https://www.devze.com 2023-04-06 10:19 出处:网络
I开发者_Python百科 have create 3 buttons on the left menu for \"Cars,\" \"Music,\" and \"Games\"

I开发者_Python百科 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?


Use jquery load function


<!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>
0

精彩评论

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