使用jQuery隐藏所有其他div

时间:2014-06-03 02:31:25

标签: jquery html hide

当我点击一个按钮时,它会显示一个div id。我也希望它隐藏所有其他div id。有人可以指点我使用jQuery进行如何执行此操作的教程吗?我目前的代码如下:

$('#show_link_group').click(function() {
  $('#link_group').show();
});

在显示我的#link_group之后,我希望它隐藏所有其他div。

4 个答案:

答案 0 :(得分:1)

我建议给你所有的div一个类名,并用它来隐藏它们。

<div class="alert" id="item-one"></div>
<div class="alert" id="item-two"></div>
<div class="alert" id="item-three"></div>

然后使用jQuery

// Hide all divs with a class of alert then show the div with id of item-one
$('.alert').hide().filter('#item-one').show();

答案 1 :(得分:1)

$("#show_link_group").click(function()
{
     $('div').hide();
     $('#'+$(this).attr('name')).show();   
});

Working Demo

答案 2 :(得分:1)

您可以使用:not()

e.g。 $("div:not(#idOfDivToBeShown)").hide();$("div#idOfDivToBeShown").show();

请参阅Demo

答案 3 :(得分:0)

这会在页面上隐藏所有其他DIV,但会显示带有id="link_group"

的DIV
$('#show_link_group').click(function() {
    $('div').hide();
    $('#link_group').show();
});

但是,如果您希望仅隐藏某些其他DIV,则可以将类分配给其他DIV,然后使用该类隐藏所有DIV。这是一个例子:

jsFiddle Demo

<div id="one"   class="hideable">This is div one</div>
<div id="two">DIV two - not of the HIDEABLE class</div>
<div id="three" class="hideable">This is div three</div>
<div id="link_group" class="hideable">This is div LINK_GROUP</div>
<div id="four"  class="hideable">This is div four</div>
<div id="five"  class="hideable">This is div five</div>

<input type="button" id="show_link_group" value="Hide the rest" />

$(function(){
    $('#show_link_group').click(function() {
        $('.hideable').hide();
        $('#link_group').show();
    });

});