简体   繁体   English

如何使用JQuery在再次单击时隐藏div?

[英]How do I use JQuery to hide a div on click again?

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. 使用上面的脚本,我可以在单击#clicker时显示.show_this,但是在再次单击#clicker时我想将其隐藏。 How can I tweak my code to do that? 如何调整我的代码来做到这一点?

I did some research and it seemed that by using e.preventDefault(); 我做了一些研究,似乎是通过使用e.preventDefault();e.preventDefault(); I would be able to achieve that but it didn't work. 我能够实现这一目标,但没有成功。

You can use toggle(); 您可以使用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.com/toggle Api文档: http : //api.jquery.com/toggle

Also event.preventDefault(); 还有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. 将无法执行此操作,尽管如果.show-this是定位标记非常有用,因为它会阻止默认操作并且将遵循链接。

Use .toggle() instead. 使用.toggle()代替。

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

jsFiddle example jsFiddle示例

You can do this using the .toggle() method like: 您可以使用.toggle()方法执行此操作,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM