我正在尝试制作一个网页,点击按钮显示和隐藏div,我现在的问题是;
如何通过单击特定按钮隐藏所有其他div。
CodeJava:
function showHide(divId){
var theDiv = document.getElementById(divId);
if(theDiv.style.display=="none"){
theDiv.style.display="block";
}else{
theDiv.style.display="none";
}
}
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>
因此,如果您点击div2,我希望其他人隐藏显示。
答案 0 :(得分:2)
首先,添加一种方法来识别所有带内容的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>
然后,使用此功能显示/隐藏内容div标签:
function showHide(divId){
$(".contents").not("#" + divId).hide();
$("#" + divId).show();
}
这假设您页面标题中的某个位置已正确包含jQuery库。
答案 1 :(得分:0)
通常你用CSS Classes
来做<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>
使用Jquery,您可以轻松访问您单击的对象:
$('.toclick').click(function(){
var doNotDisappear = $(this).attr('id'); //get id of div
$('#'+doNotDisappear).next('tohide').removeClass('tohide');
$('tohide').hide(); //make the other disappear
});
答案 2 :(得分:0)
可能的一个:
function showHide(btn){
$(btn).next('.showhide').toggle().siblings('.showhide').hide();
}
遵循相关的HTML:
<div onclick="showHide(this)">This is the button.</div>
<div class="showhide">This is a div to hide and show.</div>
<!-- etc... -->