![](/img/trans.png)
[英]How to hide and show a <div> onclick when there's already an action for click?
[英]How to hide div when it's already open?
我想不出更好的標題,所以我會盡可能清楚地解釋我的問題。 我是JQuery的新手,所以這可能是一個非常簡單的問題。
我有一些帶有按鈕的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();
});
例如,當show_1
可見時,我點擊了div2中的按鈕,我希望show_2
出現,它會出現,但show_1
要消失。
有人能指出我正確的方向嗎?
你可以隱藏所有以“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>
文件的結構是固定的嗎? 是這樣......我想最簡單的方法就是做以下事情:
$('.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(); } })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.