Javascript jquery;如何显示单击div并隐藏所有其他div

Javascript jquery;如何显示单击div并隐藏所有其他div,javascript,jquery,html,css,onclick,Javascript,Jquery,Html,Css,Onclick,我试图制作一个网页,你点击一个按钮来显示和隐藏一个div,我现在的问题是 如何通过单击特定按钮隐藏所有其他div 代码Java: function showHide(divId){ var theDiv = document.getElementById(divId); if(theDiv.style.display=="none"){ theDiv.style.display="block"; }else{ theDiv.style.di

我试图制作一个网页,你点击一个按钮来显示和隐藏一个div,我现在的问题是

如何通过单击特定按钮隐藏所有其他div

代码Java:

function showHide(divId){
    var theDiv = document.getElementById(divId);
    if(theDiv.style.display=="none"){
        theDiv.style.display="block";
    }else{
        theDiv.style.display="none";
    }    
}
代码HTML:

    <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>
这是按钮。
这是一个隐藏和显示的div。
这是按钮。
这是一个隐藏和显示的div。
这是按钮。
这是一个隐藏和显示的div。

因此,如果您单击div2,我希望其他部分显示为隐藏

首先,添加一种方法,用内容标识所有div标记(通常使用类完成),如下所示:


这假设您在页面标题的某个地方正确地包含了jQuery库。

通常使用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>
可能的一个:

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... -->
这是按钮。
这是一个隐藏和显示的div。

看起来您的做法不对。以下是我想你正在寻找的功能:这个问题不需要被否决,因为手风琴肯定会符合要求,但如果他需要在外观和感觉方面进行更多定制,那么独立于UI库进行操作可能是必要的。
$('.toclick').click(function(){
   var doNotDisappear =  $(this).attr('id'); //get id of div
   $('#'+doNotDisappear).next('tohide').removeClass('tohide');
   $('tohide').hide(); //make the other disappear
});
function showHide(btn){   
    $(btn).next('.showhide').toggle().siblings('.showhide').hide();
}
<div onclick="showHide(this)">This is the button.</div>
<div class="showhide">This is a div to hide and show.</div>
<!-- etc... -->