簡體   English   中英

使用jQuery顯示和隱藏div?

[英]show and hide divs using jquery?

我有兩個鏈接和2個div。 我想顯示div 1而div 2隱藏。 當顯示div 2時,我希望div 1隱藏。 我嘗試編寫此代碼,但似乎不起作用。(僅第一部分。videosdiv隱藏了)

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

將綁定單擊處理程序的代碼放入dom ready回調中,或者在兩個div尚未就緒時執行該代碼。

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

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

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

其他解決方案效果很好,但是這里是一個較短的版本

$(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

上述查詢還有另一種替代方法:

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

您可以在代碼倉上嘗試上述解決方案http://codebins.com/codes/home/4ldqpbm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM