簡體   English   中英

如何使div隱藏onclick並在再次單擊時顯示它?

[英]How do I make a div hide onclick and make it show when it's clicked again?

我有以下代碼:

<script>
(function ($) {
    $(document).ready(function () {
        $("#thisclick, #thisclick2").click(function () {
            if ($('.example').is(":hidden")) {
                $(this).html($(this).html().replace(/Hide/, 'Show'));
            } else {
                $(this).html($(this).html().replace(/Show/, 'Hide'));
            }
            // Do it afterwards as the operation is async
            $(".example").hide();
        });
    });
})(jQuery);
</script>

當前代碼的工作方式是,如果單擊#thisclick ,則會隱藏#example 這是我所需要的,但是當再次單擊#thisclick時,我希望它顯示#example 使用上面的代碼,它將無法正常工作。 我必須怎么做才能做到這一點?

您應該可以將代碼更改為如下所示,以使其正常工作:

(function ($) {
    $(document).ready(function() {
    $("#thisclick").click(function () {
        $("#example").slideToggle("slow");
        });
    });
})(jQuery);

這里是一個快速示例的鏈接: http : //jsfiddle.net/andyjmeyers/szmXp/

你期望像

<button>This click</button>
<p style="display: none">Example</p>

<script>
$("button").click(function () {
$("p").toggle();
});
</script>

請在http://jsfiddle.net/X5r8r/1107/上進行檢查

<script>
    (function ($) {
          $(document).ready(function() {
          $("#thisclick").click(function () {
             if ($('#example').is(":hidden")) {
                 $(this).html($(this).html().replace(/Hide/, 'Show'));

             } else {
                 $(this).html($(this).html().replace(/Show/, 'Hide'));
             }
             // Do it afterwards as the operation is async
             $("#thisclick").slideToggle("slow");
             if($("#example").attr("isHidden") == "1")
                  $("#example").slideToggle("slow");
             $("#example").attr("isHidden","1");
          });
      });
        })(jQuery);
        </script>

你可以這樣做:

$("#thisclick").click(function () {
   if ($('#example').hasClass("hidden"))
   {
      $('#example').removeClass("hidden");
      $('#example').show();
   }
   else
   {
      $('#example').addClass("hidden");
   }
}

或更容易:

$("#thisclick").click(function () {
   $('#example').toggleClass("hidden");
}

定義樣式”:

.hidden
 { display:none;}

暫無
暫無

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

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