1

我正在尝试制作一个网页,您可以在其中单击按钮以显示和隐藏 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>

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

4

3 回答 3

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 库。

于 2013-09-19T15:04:42.457 回答
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... -->
于 2013-09-19T15:11:23.270 回答
0

通常,您使用 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>

使用 Jquery,您可以轻松访问您单击的对象:

$('.toclick').click(function(){
   var doNotDisappear =  $(this).attr('id'); //get id of div
   $('#'+doNotDisappear).next('tohide').removeClass('tohide');
   $('tohide').hide(); //make the other disappear
});
于 2013-09-19T15:10:31.837 回答