2016-08-01 3 views
2

ボタンをクリックすると、1つのdivコンテンツを別のコンテンツに変更しようとしています。また、コンテンツエリアの別々のdivの間にアニメーションを追加したいと思います。私は両方の部門間を切り替えることを希望します。 btn1を押すとsection1の商品を表示し、btn2を押すとsection2の商品を表示します。JQuery .replaceWith()または.html()

HTML

<button id="btn1" type="button" class="btn">btn1</button> 
<button id="btn2" type="button" class="btn">btn2</button> 

<div id="section1"> 
<!-- content goes here --> 
</div> 
<div id="section2"> 
<!-- content goes here --> 
</div> 

jQueryの

$(document).ready(function() { 
    var section1 = $('#section1') 
    var section2 = $('#section2') 

    $('#btn1').click(function() { 
    $('#section1').html($('#section2').html()); 
    }); 

    $('#btn2').click(function() { 
    $('#section2').html($('#section1').html()); 
    }); 
}); 

任意の助けもいただければ幸いです! :)

答えて

2

あなたがshow()hide()を使用して方がいいでしょう:

$('#btn1').click(function() { 
    $('#section1').show(); 
    $('#section2').hide(); 
}); 

$('#btn2').click(function() { 
    $('#section2').show(); 
    $('#section1').hide(); 
}); 

それはHTMLをいじりよりも簡単です。また、高度化すると、フェーディングなどのさまざまな効果を試すことができます。 Hereは、表示と非表示に使用できるさまざまなjQueryエフェクトのデモです(表示と非表示を伴わない他のエフェクトもあります)。 (このデモでは、同様にインストールされているjQueryの-UIが必要です。)

+0

驚くばかりを見て!これは機能します。ありがとうございました!私は以前これを試しましたが、動作させるように見えませんでした。どのようにフェードインを実装しますか?私はそのdiv内の他のdivを1つずつ作成することを考えていました。 – ColeGauthier

+1

パフォーマンスの理由や登録されたDOMイベントの方が優れているとも言えます。隠されて表示される要素は、DOMイベント(click、mouseupなど)を保持します。 –

+0

[this](http://api.jqueryui.com/fade-effect/)をご覧ください。これは '$( '#section1')と同じくらいシンプルにすることができます。show( 'fade');'。 – BobRodes

0

のような笑楽しみに取って代わる

$(document).ready(function() { 
 
    $('button#btn1').bind('click', function() { 
 
    temp = $('div#section1').text(); 
 
    $('div#section1').text($('div#section2').text()); 
 
    $('div#section2').text(temp); 
 
    }); 
 
    $('button#btn2').bind('click', function() { 
 
    temp = $('div#section2').text(); 
 
    $('div#section2').text($('div#section1').text()); 
 
    $('div#section1').text(temp); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<p><button id="btn1" type="button" class="btn">btn1</button></p> 
 
<p><button id="btn2" type="button" class="btn">btn2</button></p> 
 
<p><hr></p> 
 
<p><div id="section1">Lorem ipsum dolor sit amet.</div></p> 
 
<p><div id="section2">Lorem consectetur adipiscing elit. Maecenas in.</div></p>

+0

あなたの返答いただきありがとうございます、上記の受け入れられたコードはすばらしく機能します! – ColeGauthier

+0

@ColeGauthierそれは大丈夫です – KingRider

関連する問題