admin管理员组

文章数量:1317898

CODE:

<script type="text/javascript">
$(document).ready(function() {
    $("#clicker").click(function() {
        $(".show_this").show();
        e.preventDefault();
    });
});
</script>

Using the script above I am able to show .show_this on clicking #clicker but on clicking #clicker again i want to hide it. How can I tweak my code to do that?

I did some research and it seemed that by using e.preventDefault(); I would be able to achieve that but it didn't work.

CODE:

<script type="text/javascript">
$(document).ready(function() {
    $("#clicker").click(function() {
        $(".show_this").show();
        e.preventDefault();
    });
});
</script>

Using the script above I am able to show .show_this on clicking #clicker but on clicking #clicker again i want to hide it. How can I tweak my code to do that?

I did some research and it seemed that by using e.preventDefault(); I would be able to achieve that but it didn't work.

Share Improve this question asked Sep 4, 2013 at 17:21 starbucksstarbucks 3,01610 gold badges42 silver badges53 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You can use toggle();

$(".show_this").toggle();

This will toggle every time, so if it is hidden it will show it and vice versa

Api Documentation: http://api.jquery./toggle

Also event.preventDefault(); will not be able to do this, though it is useful if the .show-this is a anchor tag because it will prevent the default action and that is to follow the link.

Use .toggle() instead.

$(document).ready(function() {
    $("#clicker").click(function(e) {
        $(".show_this").toggle();
        e.preventDefault();
    });
});

jsFiddle example

You can do this using the .toggle() method like:

$(document).ready(function() {
    $("#clicker").click(function(e) {  // call the event variable 'e' first here
        e.preventDefault();
        $(".show_this").toggle();            
    });
});

本文标签: javascriptHow do I use JQuery to hide a div on click againStack Overflow