2016-08-01 166 views
2

我試圖改變一個div內容到另一個,反之亦然當按鈕被點擊。我還想在內容區域中爲單獨的div添加一些動畫。我想要它在兩個div之間切換。對於intsance,在按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在一段時間內褪色。 – ColeGauthier

+1

我還提到它更好的性能原因和註冊的DOM事件。隱藏然後顯示的元素可以保留它的DOM事件(點擊,鼠標等)。 –

+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