[英]jquery; how do I show the click-on div and hide all the others
I'm trying to make a webpage where you click on a button to show and hide a div, my problem now is; 我正在尝试制作一个网页,您在其中单击按钮以显示和隐藏div,现在的问题是;
How do I hide all of the other div's by clicking on a specific button. 如何通过单击特定按钮来隐藏所有其他div。
CodeJava: CodeJava:
function showHide(divId){
var theDiv = document.getElementById(divId);
if(theDiv.style.display=="none"){
theDiv.style.display="block";
}else{
theDiv.style.display="none";
}
}
CodeHTML: CodeHTML:
<div id="div" onclick="showHide('divcontent')"> This is the button. </div>
<div id="divcontent"> This is a div to hide and show. </div>
<div id="div2" onclick="showHide('divcontent2')"> This is the button. </div>
<div id="divcontent2"> This is a div to hide and show. </div>
<div id="div3" onclick="showHide('divcontent3')"> This is the button. </div>
<div id="divcontent3"> This is a div to hide and show. </div>
So if you click on div2, I want the others to be displayed hidden. 因此,如果您单击div2,我希望其他显示为隐藏。
First, add a way to identify all of your div tags with content (generally done with a class) like so: 首先,添加一种方法来标识所有具有内容的div标签(通常是通过类完成),如下所示:
<div id="div" onclick="showHide('divcontent')"> This is the button. </div>
<div class="content" id="divcontent"> This is a div to hide and show. </div>
<div id="div2" onclick="showHide('divcontent2')"> This is the button. </div>
<div class="content" id="divcontent2"> This is a div to hide and show. </div>
<div id="div3" onclick="showHide('divcontent3')"> This is the button. </div>
<div class="content" id="divcontent3"> This is a div to hide and show. </div>
Then, use this function to show/hide content div tags: 然后,使用此功能显示/隐藏内容div标签:
function showHide(divId){
$(".contents").not("#" + divId).hide();
$("#" + divId).show();
}
This assumes that somewhere in your page header you've properly included the jQuery library. 假设您在页面标题中的某个位置正确地包含了jQuery库。
Generally you do that with CSS Classes 通常,您可以使用CSS类来做到这一点
<div id="div" class="toclick"> This is the button. </div>
<div id="divcontent" class="tohide"> This is a div to hide and show. </div>
<div id="div2" class="toclick"> This is the button. </div>
<div id="divcontent2" class="tohide"> This is a div to hide and show. </div>
<div id="div3" class="toclick"> This is the button. </div>
<div id="divcontent3" class="tohide"> This is a div to hide and show. </div>
With Jquery you can easily access the object you clicked on: 使用Jquery,您可以轻松访问您单击的对象:
$('.toclick').click(function(){
var doNotDisappear = $(this).attr('id'); //get id of div
$('#'+doNotDisappear).next('tohide').removeClass('tohide');
$('tohide').hide(); //make the other disappear
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.