1

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.

4

3 回答 3

4

您可以使用toggle();

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

这将每次切换,所以如果它被隐藏它会显示它,反之亦然

Api 文档:http ://api.jquery.com/toggle

event.preventDefault();将无法执行此操作,但如果.show-this是锚标记很有用,因为它会阻止默认操作,即跟随链接。

于 2013-09-04T17:23:15.977 回答
3

改为使用.toggle()

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

jsFiddle 示例

于 2013-09-04T17:23:13.937 回答
2

您可以使用以下.toggle()方法执行此操作:

$(document).ready(function() {
    $("#clicker").click(function(e) {  // call the event variable 'e' first here
        e.preventDefault();
        $(".show_this").toggle();            
    });
});
于 2013-09-04T17:23:35.717 回答