简体   繁体   中英

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

I have this code:

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

The way the current code works is that if #thisclick is clicked it hides #example . Which is what I require but when #thisclick is clicked again i want it to show #example . Using the above code, it won't work. What must I do to achieve this?

You should be able to change your code to as follows to get it to work:

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

Here is a link to a quick sample: http://jsfiddle.net/andyjmeyers/szmXp/

Are you expecting like

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

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

Please check it on 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>

You can do this:

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

or more easily:

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

define style":

.hidden
 { display:none;}

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