2013-02-01 162 views
0

我正在尋找一些簡單的jquery問題的指導。使用切換或顯示/隱藏切換Div內容

我試圖按下按鈕時顯示/隱藏內容。我有2個按鈕。我想要一個按鈕來顯示1 div的內容,並且我想要另一個按鈕來隱藏第一個div的內容並顯示第二個div的內容。

我創建了一個的jsfiddle這裏http://jsfiddle.net/Yn3tt/1/

我的想法是,我可以切換的一類叫做noDisplay這將坐上格設置我不想顯示(從而隱藏它)我不知道的jquery要做到這一點?

我也不確定這是否更容易使用jQuery的顯示/隱藏類來實現這一目標?

感謝

我的HTML如下:

<button id="opt1">Option 1</button> 
<button id="opt2">Option 2</button> 

<div class="yesDisplay"> 
<p>Show me when I press Option 1 and hide Option 2 content</p> 
</div> 

<div class="noDisplay"> 
<p>Show me when I press Option 2 and Hide Option 1 content</p> 
</div> 

和我的CSS簡直是

.noDisplay{display:none;} 

.yesDisplay{display:block;} 

演示是在這裏http://jsfiddle.net/Yn3tt/1/

+0

你可能要重新考慮你的類的命名和使用。看起來這可能會導致一些混亂與否定。這個類似於jquery –

+0

@UrbanBjörkman好點!雖然show hide示例似乎在下面工作...不知道如何做切換方法 – Redwall

回答

3

使用hide()show() jQuery函數.. click()Ë發泄火的時候,點擊......我做了這個儘可能的簡單,這樣你就會很容易理解

CSS

.noDisplay{display:none;} 
.yesDisplay{display:none;} 

JQUERY

$('#opt1').click(function(){ 
    $('.yesDisplay').show(); //class selector for the div to show 
    $('.noDisplay').hide(); 
}); 

$('#opt2').click(function(){ 
    $('.noDisplay').show(); 
    $('.yesDisplay').hide(); 
}); 

但是你可以使用函數像.. toggle()slideToggle()以減少您的代碼

fiddle here

+0

感謝您的幫助 – Redwall

+0

歡迎...有趣的編碼.. :) – bipen

+0

切換可以是非常緩慢。在此處查看測試:[http://jsperf.com/](http://jsperf.com/speed-difference-of-toggling-of-visibility-jquery-vs-pu) –

1

更新您的提琴: http://jsfiddle.net/Yn3tt/3/

$('#opt1').click(function(){ 
    $('.yesDisplay').show(); 
    $('.noDisplay').hide(); 
}); 

$('#opt2').click(function(){ 
    $('.yesDisplay').hide(); 
    $('.noDisplay').show(); 
}); 
+0

感謝您的幫助 – Redwall

1
u can do this without css ,i mean using jquery 
<script> 
     $(".yesDisplay").hide(); 
     $(".noDisplay").hide(); 
    $("#opt1").click(function(){ 
     $(".yesDisplay").show(); 
    $(".noDisplay").hide(); 
}); 


    $("#opt2").click(function(){ 
     $("noDisplay").show(); 
    $(".yesDisplay").hide(); 
}); 
</script> 

<button id="opt1">Option 1</button> 
<button id="opt2">Option 2</button> 

<div class="yesDisplay"> 
<p>Show me when I press Option 1 and hide Option 2 content</p> 
</div> 

<div class="noDisplay"> 
<p>Show me when I press Option 2 and Hide Option 1 content</p> 
</div> 

ü可以在這裏查看http://jsfiddle.net/Yn3tt/7/