简体   繁体   中英

show and hide divs using jquery?

I have two links and 2 divs. I want to show div 1 while div 2 is hidden. and when I show div 2, I want div 1 to be hidden. I tried to write this code but it seem not working.(only the first part. videos div is hidden)

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
$(document).ready(function() {
   $('#videos').hide();
 });

$('#show_images').click(function(){
    $('#videos').hide();
    $('#images').show();
});

    $('#show_videos').click(function(){
        $('#images').hide();
        $('#videos').show();
    });

    </script>
    <a id="show_images" class="button" href="#">Images</a>
    <a id="show_videos" class="button" href="#">Videos</a>

<div id="images" class="images"></div>
<div id="videos" class="videos"></div>

Put the code which bind click handler into the dom ready callback, or the code executes when the two div are not ready.

$(document).ready(function() {
   $('#videos').hide();

  $('#show_images').click(function(){
    $('#videos').hide();
    $('#images').show();
  });

  $('#show_videos').click(function(){
    $('#images').hide();
    $('#videos').show();
  });
});

The other solutions work perfectly, but here is a shorter version

$(document).ready(function()
   {
   $('#videos').hide();

   $('[id^=show_]').click(function(){
      $('#videos').toggle();
      $('#images').toggle();
      });
   });
$(document).ready(function() {
   $('#videos').hide();


$('#show_images').click(function(){
    $('#videos').hide();
    $('#images').show();
});

$('#show_videos').click(function(){
    $('#images').hide();
    $('#videos').show();
});
}); //close document ready here

There is another alternate way for above query:

$(function(){
   $('#show_images').click(function(){
      $('#videos').hide();
      $('#images').show();
  });
  $('#show_videos').click(function(){
        $('#images').hide();
        $('#videos').show();
  });
  $('#show_images').trigger('click');
});

You can try above solution on codebins http://codebins.com/codes/home/4ldqpbm

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