简体   繁体   中英

Using jQuery show() / hide()

I am using show() and hide() in my jsp page, and it is working fine, but I am having trouble figuring out a way to hide my table once it is shown. HTML EX:

<button id="b1">show 1</button>
<button id="b2">show 2</button>
<div class="hidden" id="d1">
<div class="hidden" id="d2">

So basically I want to show div1 when button1 is clicked, and show div2 when button2 is clicked. I am using hide() / show() because I never want both to show at the same time. So here is my script:

  $('#b1').click(function(){
    $('#d1').show();
    $('#d2').hide();
  });

  $('#b2').click(function(){
    $('#d2').show();
    $('#d1').hide();
  });

So this works fine, as far as showing only one at a time, but I want to add some script to this to make it where if div2 is showing, I can click on button2 and make div2 hide, and the same thing for div1 . I know this is confusing so if you have any questions please ask. thanks.

I think you want this:

$('#b1').click(function(){
    $('#d1').toggle();
});

$('#b2').click(function(){
    $('#d2').toggle();
});

If you need to still make it so that only one can be shown then probably something like this:

$('#b1').click(function(){
    if($('#d1').toggle().is(":visible")){
       $('#d2').hide();
    }
});

$('#b2').click(function(){
    if($('#d2').toggle().is(":visible")){
       $('#d1').hide();
    }
});

I think you need this

$('#b1').click(function(){
    $('#d2').hide();
     $('#d1').toggle();
});

$('#b2').click(function(){
     $('#d1').hide();
     $('#d2').toggle();

});

You don't need to check anything, just toggle the first one and always hide the other one

$('#b1').click(function(){
    $('#d1').toggle();
    $('#d2').hide();
});

$('#b2').click(function(){
    $('#d2').toggle();
    $('#d1').hide();
});

There's a toggle() method that you can use instead of show/hide that will do this for you.

With no parameters, the.toggle() method simply toggles the visibility of elements:

Source: http://api.jquery.com/toggle/

  $('#b1').click(function(){
    $('#d1').toggle();
  });

  $('#b2').click(function(){
    $('#d2').toggle();
  });

if you don't use any animation, it is probably more useful to define a class in css, say, .hidden {display:"none"} and toggle it.

Thus, you code can be something like this:

$("#b1, #b2").click(function() { $("#d1, d2").toggleClass("hidden") })

Try this one, if you want, and tell us, whether it works )

You can check if something is visible by this $('#someDiv:visible') and then do appropriate handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM