显示隐藏div jQuery [英] show hide div jQuery
问题描述
我正在尝试为我的网站设置show hide div功能.但是我有多个显示隐藏按钮的问题.所以问题是当我单击容器div中的显示按钮时,所有蓝色div都会自动显示.
I am trying to make a show hide div function for my website. But I have one problem with multiple show hide button. So the problem is that when I click show button in container div then all blue div showing automatically.
您可以看到 演示 .
You can see a DEMO.
HTML :
<div class="container">
<div class="div">
<div id="hidediv">Hide</div>
</div>
<div class="test"></div>
<div id="showdiv">Show</div>
</div>
<div class="container">
<div class="div">
<div id="hidediv">Hide</div>
</div>
<div class="test"></div>
<div id="showdiv">Show</div>
</div>
JavaScript :
$(document).ready(function() {
$("#hidediv").hide();
$('#showdiv').click(function() {
$('.div').toggle("slide");
$("#showdiv").hide();
$("#hidediv").show();
});
$('#hidediv').click(function() {
$('.div').toggle("slide");
$("#hidediv").hide();
$("#showdiv").show();
});
});
当用户单击容器show div中的show按钮时,我只想显示此div. 我希望你能理解我.
When the user clicks show button in container show div, then I only want to show this div. I hope you can understand me.
推荐答案
首先,您应该使用类而不是id.固定的HTML变为:
First of all you should use classes instead of id. Fixed HTML becomes:
<div class="container">
<div class="div">
<div class="hidediv">Hide</div>
</div>
<div class="test"></div>
<div class="showdiv">Show</div>
</div>
,依此类推.这是最灵活的方法,因为现在您可以根据需要添加任意多个可折叠容器,而无需更改JS代码.
and so on. This is the most flexible approach, because now you can add as many collapsible containers as you need without need to change JS code.
JavaScript代码(使用on
方法可以更有效地处理事件):
Javascript code then can be (with on
method for more effective event handling):
$('.container').on('click', '.showdiv', function(e) {
var $container = e.delegateTarget;
$('.div', $container).toggle('slide');
$('.showdiv', $container).hide();
$('.hidediv', $container).show();
})
.on('click', '.hidediv', function(e) {
var $container = e.delegateTarget;
$('.div', $container).toggle("slide");
$(".hidediv", $container).hide();
$(".showdiv", $container).show();
});
这篇关于显示隐藏div jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!