2011-02-03 58 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