jQueryはコンテンツの表示と非表示を切り替えます

コンテンツを表示および非表示にするjQueryトグルの例

The requirement:[表示]ボタンをクリックすると折りたたみ可能なコンテンツを表示し、[非表示]ボタンをクリックすると折りたたみ可能なコンテンツを非表示にする必要があります。

The solution:jQuerytoggle()関数。

デモ:「表示」ボタンをクリックします。

1. 折りたたみ可能なコンテンツ

以下は、折りたたみ可能なコンテンツのHTMLの例です。

Use jQuery toggle to hide/show collapse content

上記の<div id="collapse1" style="display:none">の「div」要素は非表示になっています。 [表示]ボタンをクリックしたときにコンテンツを表示するには、次のような[表示]ボタンのクリックイベントを作成する必要があります。

$('.nav-toggle').click(function(){
    //logic to show/hide collapsable content
});

2. セレクターを入手する

属性hrefから折りたたみコンテンツのセレクターを取得します。

var collapse_content_selector = $(this).attr('href');

3. 表示と非表示に切り替え

jQueryトグルを使用して、以下のように折りたたみ可能なコンテンツを表示/非表示します。

var toggle_switch = $(this);
$(collapse_content_selector).toggle(function(){
    if($(this).css('display')=='none'){
        toggle_switch.html('Show');//change the button label to be 'Show'
    }else{
        toggle_switch.html('Hide');//change the button label to be 'Hide'
    }
});

4. 完全な例


 
    jQuery toggle to display and hide content

    
    
        
    
    
        

jQuery toggle() to hide/show collapse content

ソースコードをダウンロード

ダウンロード–jQuery-toggle-to-display-hide-content.zip(1kb)