2011-02-03 60 views
0

我在这里有一个相对简单的问题。最简单的方法来按按钮点击加载DIV?

我需要的是这个;我需要有一个页面,顶部有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,则会在“content”DIV内加载“content5”DIV,例如。

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

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

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

非常感谢

+0

您是否希望以前按钮点击的内容保留在#内容中? – ocodo 2011-02-03 07:14:11

回答

4

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

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

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

这将增加一个点击事件处理所有<button>节点。单击时,它会查找当前单击按钮(.index()help)的索引并使用此值查询元素标识符<div>。一旦找到,使用.html()help来获取和设置值。

+0

我在想同样的事情,但你之前发布......任何方式upvaoted为答案 – Vivek 2011-02-03 07:19:37

0

试试这个

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

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

// etc 

这种方式清除现有的内容和副本的正确的div到主#内容股利。

+0

我在猜测,当你点击另一个按钮时,Sam不希望上一个按钮单击的内容保持不变。 (然而,这是一个纯粹的假设。) – ocodo 2011-02-03 07:15:03

+1

我正在编辑和迭代改进它:)经过几次编辑它几乎完全相同的另一个答案,所以我已经停在那里。 – 2011-02-03 07:24:09