2012-05-03 89 views
-1

我有兩個DIV標籤,分別是respond-1和respond-2。我想用按鈕選擇這些div。當我點擊respond1Button它應該顯示響應-1 div和類似的點擊repond2Button,響應-2 div將被顯示。使用jQuery按鈕選擇DIV

默認頁面應該顯示respond-1 div。

+2

你能發佈一些你的html嗎? – shanabus

回答

2

對於像下方的HTML,

<div id="container"> 
    <div id="respond-1" class="responses">Respond 1</div> 
    <div id="respond-2" class="responses" style="display: none" >Respond 2</div> 
</div> 
<button id="respond1Button">Respond 1</button> 
<button id="respond2Button">Respond 2</button> 

下面是腳本來顯示基於相應的按鈕,點擊/隱藏,

$(function() { 
    var $respond1 = $('#respond-1'); 
    var $respond2 = $('#respond-2'); 
    var $responses = $('.responses'); 

    $('#respond1Button').click(function() { 
     $responses.hide(); 
     $respond1.show(); 
    }); 

    $('#respond2Button').click(function() { 
     $responses.hide(); 
     $respond2.show(); 
    }); 
}); 

DEMO

0

你在找這樣的嗎?

<div id="respond-1">First Response<div> 
<div id="respond-2" style="display:none;">Second Response<div> 

<button type="button" onclick="$('#respond-1').show();$('#respond-2').hide():">repond1Button</button> 

<button type="button" onclick="$('#respond-2').show();$('#respond-1').hide():">repond2Button</button> 
0

您可以使用.click事件來綁定點擊處理程序。使用$('#id')選擇具有ID的元素,因此將這兩個元素組合在一起可以輕鬆創建使div可見的按鈕。

<div id="respond-1"></div> 
<button id="respond1Button">Show Respond 1</button> 

// on DOM ready... 
$(function() { 
    // Select the divs 
    var resp1 = $('#respond-1'); 

    // Hide them to start 
    resp1.hide(); 

    // Bind click handlers 
    $('#respond1Button').click(function() { 
     resp1.show(); 
    }); 
}); 
0

請注意,您不能具有多個具有相同ID屬性的itens,並且DIV標籤沒有名爲NAM的屬性E.

在這種情況下,我想最好的選擇是爲BUTTON和DIV定義一個類'respond-1'。根據所點擊的按鈕的類別,我們顯示通訊員DIV。 (對不起,任何英文錯誤,它不是我的母語):)

$(document).ready(function(){ 

    $('button.respond-1, button.respond-2').click(function(){ 

     $('div.respond-1, div.respond-2').hide(); 
     $('div.' + $(this).attr('class')).show(); 

    }); 

}); 
相關問題