按钮点击动态加载DIV的最简单方法?

时间:2011-02-03 07:04:25

标签: javascript jquery html dynamic

我在这里有一个相对简单的问题。

我需要的是这个;我需要一个页面,顶部有5个按钮,下面有DIV(最初隐藏)。单击一个按钮时,它会将内容加载到DIV中(以另一个DIV的形式) 例如

[Button 1] [Button 2] [Button 3] [Button 4] [Button 5] //5 buttons or links

<div id="content">
 // area for content to be loaded
</div>

<div id="content1">
//could be a table or image
</div>

<div id="content2">
//could be a table or image
</div>

<div id="content3">
//could be a table or image
</div>

<div id="content4">
//could be a table or image
</div>

<div id="content5">
//could be a table or image
</div>

在上面的示例中,当用户加载页面时,他们会看到5个按钮。如果他们按下按钮5,它会在“内容”DIV中加载“content5”DIV,例如

<div id="content">
 <div id="content5">
</div>
</div>

如果选择了另一个按钮,则会加载它的内容。

可以使用jQuery或简单的JavaScript实现。

非常感谢

3 个答案:

答案 0 :(得分:4)

您需要在所有按钮上绑定单击处理程序。此特定示例中的智能方法是,使用元素的索引来确定哪个div属于button

$('button').bind('click', function() {
    $('div#content').html($('div#content' + ($(this).index()+1)).html());
});

演示http://www.jsfiddle.net/8f8jt/

这将向所有<button>个节点添加一个click事件处理程序。单击时,它会查找当前单击按钮(.index()help)的索引,并使用此值查询一致的<div>元素id。找到后,使用.html()help获取并设置值。

答案 1 :(得分:1)

您也可以使用jQueryUI tabs,但需要额外的脚本。

答案 2 :(得分:0)

试试这个

$('#button1').click(function() {
    $("#content").html(("#content1").html());
});

$('#button2').click(function() {
    $("#content").html(("#content2").html());
});

// etc

这样可以清除所有现有内容,并将正确的div复制到主#content div。