[英]How to hide div when it's already open?
I couldn't think of any better title, so I will try to explain my question here as clear as possible. 我想不出更好的标题,所以我会尽可能清楚地解释我的问题。 I'm quite a newbie in JQuery so this is probably a very easy question.
我是JQuery的新手,所以这可能是一个非常简单的问题。
I have some divs with a button on it. 我有一些带有按钮的div。 When you click the button, another div should pop-up.
单击该按钮时,应弹出另一个div。 My question is: How can I make the div, which is already open, close when clicking on another button?
我的问题是:如何在点击另一个按钮时使已经打开的div关闭?
I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/ 我用一些示例代码做了一个小提琴: http : //jsfiddle.net/zuvjx775/1/
And the example code here: 这里的示例代码:
HTML: 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: JQuery的:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
$('.show_'+id).show();
});
When show_1
for example is visible, and I click on the button in div2, I want show_2
to come up, which it does, but show_1
to dissapear. 例如,当
show_1
可见时,我点击了div2中的按钮,我希望show_2
出现,它会出现,但show_1
要消失。
Can someone point me in the right direction? 有人能指出我正确的方向吗?
You can hide all divs that their class starts with 'show' before show the one you want. 你可以隐藏所有以“show”开头的div,然后再显示你想要的那个。 For example:
例如:
$('.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>
Is the structure of the document fixed? 文件的结构是固定的吗? is so... I guess the easiest way of doing this is to just do the following:
是这样......我想最简单的方法就是做以下事情:
$('.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.