2012-05-03 11 views
-1

私は2つのDIVタグ、すなわちレスポンス1とレスポンス2を持っています。私はこれらのdivをボタンで選択したいと思います。私がrespond1Buttonをクリックすると、それはrespond-1 divを表示し、同様にrepond2Buttonをクリックすると、respond-2 divが表示されます。JQueryを使用してボタンでDIVを選択

デフォルトでは、ページにはrespond-1 divが表示されます。

+2

あなたのHTMLのいくつかを投稿できますか? – shanabus

答えて

2

以下
<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')を使用して選択されるため、これら2つを組み合わせると、divを表示させるボタンを簡単に作成できます。以下のようなHTMLの場合

<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.

この場合、最良の選択肢は、クラス 'respond-1'をBUTTONとDIVのどちらかに定義することです。クリックされたボタンのクラスに応じて、対応するDIVを表示します。 (私の母国語ではなく、英語の間違いはありません):

$(document).ready(function(){ 

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

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

    }); 

}); 
関連する問題