简体   繁体   English

单击一个按钮,它将内容加载到主要内容区域

[英]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. 我在左侧菜单上为“汽车”,“音乐”和“游戏”创建了3个按钮。当用户单击一个按钮时,应将适当的内容加载到主内容区域的DIV中。 Each button should replace the contents of anything previously displayed in the div. 每个按钮应替换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. 我创建了按钮,但不知道如何将内容加载到主内容div中或如何替换先前的内容。 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. UPDATE OK让我们澄清一下。

The code above uses jQuery lib. 上面的代码使用jQuery lib。 Look here for more info about load function. 在此处查找有关加载功能的更多信息。

If you cannot or dont want to use jQuery look here for JS solution. 如果您不能或不想使用jQuery,请在此处查找JS解决方案。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM