2014-10-30 67 views
2

我想不出任何更好的標題,所以我會盡量在這裏解釋我的問題。我在JQuery中是一個新手,所以這可能是一個非常簡單的問題。如何在div已經打開時隱藏它?

我有一些div上有一個按鈕。當你點擊按鈕時,另一個div應該彈出。 我的問題是:如何使已打開的div在單擊另一個按鈕時關閉?

我做了一些示例代碼小提琴:http://jsfiddle.net/zuvjx775/1/

和示例代碼在這裏:

HTML:

<div class="wrapper"> 
    <div class="test"> 
     <input type='button' class='showDiv' id="1" value='click!' />  
    </div> 
    <div class="show_1"> 

    </div> 
</div> 
<br> 
<div class="wrapper"> 
    <div class="test"> 
     <input type='button' class='showDiv' id="2"value='click!' /> 
    </div> 
    <div class="show_2"> 

    </div> 
</div> 

JQuery的:

$('.showDiv').on('click', function(){ 
    var id = $(this).attr('id'); 
    $('.show_'+id).show(); 
}); 

當​​例如是可見的,我點擊按鈕div2,我想show_2來了,它確實,但​​消失。

有人能指出我正確的方向嗎?

+0

注意開頭的ID與數字(比如'ID =「1」 ')在HTML5中被認爲是「不好的做法」,並且在以前的HTML規範中實際上是無效的。請參見HTML 4的id屬性的[this definition](http://www.w3.org/TR/html4/types.html#type-id),以及[this definition](http://www.w3。 org/TR/html5/dom.html#the-id-attribute)爲HTML 5. – 2014-10-31 14:44:02

回答

11

你可以在顯示你想要的一個之前隱藏他們的班級以'show'開頭的所有div。例如:

$('.showDiv').on('click', function() { 
 
    var id = $(this).attr('id'); 
 
    $("div[class^='show']").hide();//find div class starts with 'show' and hide them 
 
    $('.show_' + id).show(); 
 
});
.test { 
 
    border: 1px solid black; 
 
    height: 100px; 
 
    width: 450px; 
 
    float: left; 
 
} 
 
.show_1 { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: yellow; 
 
    float: left; 
 
    display: none; 
 
} 
 
.show_2 { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: green; 
 
    float: left; 
 
    display: none; 
 
} 
 
.wrapper { 
 
    clear: both; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="wrapper"> 
 
    <div class="test"> 
 
    <input type='button' class='showDiv' id="1" value='click!' /> 
 
    </div> 
 
    <div class="show_1"> 
 

 
    </div> 
 
</div> 
 
<br> 
 
<div class="wrapper"> 
 
    <div class="test"> 
 
    <input type='button' class='showDiv' id="2" value='click!' /> 
 
    </div> 
 
    <div class="show_2"> 
 

 
    </div> 
 
</div>

+1

謝謝!甚至沒有想到這實際上是可能的! :D – Matheno 2014-10-31 08:38:46

1

是文檔的結構固定的嗎? 是這樣...我想這樣做的最簡單的方法是隻做到以下幾點:

$('.showDiv').on('click', function(){ 
 
    var id = $(this).attr('id'); 
 
    if(id == 1){ 
 
     $('.show_1').show(); 
 
     $('.show_2').hide(); 
 
    }else{ 
 
     $('.show_2').show(); 
 
     $('.show_1').hide(); 
 
    }   
 
})

+0

在我的實際代碼中,這不是一個選項,因爲我有超過50個動態生成的div,但也許這將是一個選項給其他人:) – Matheno 2014-10-31 08:39:49