简体   繁体   English

切换显示/隐藏(jQuery)

[英]Toggle show/hide (jQuery)

There are many posts on this topic already but none that address my issue directly. 已经有很多关于该主题的帖子,但是没有一篇可以直接解决我的问题。 Here is my current setup: 这是我当前的设置:

I have a div with the ID #ptwesv ; 我有一个ID为#ptwesv的div;

and another div containing the content I want to show hide with the ID #ptwest . 另一个div包含我要显示的内容,其ID为#ptwest

The jQuery I'm using is this: 我正在使用的jQuery是这样的:

<script>
jQuery("#ptwesv").click(function(){
    jQuery("#ptwest").show();
});
jQuery("#ptwesv").click(function(){
    jQuery("#ptwest").hide();
});
</script>

This is hiding the #ptwest container correctly on click, but then doesn't show the conatiner when I click the trigger element ( #ptwesv ) again. 这会在单击时正确隐藏#ptwest容器,但是当我再次单击触发元素( #ptwesv )时,不会显示conatiner。 I presume this is because once the element has been hidden, clicking on the trigger again is causing the actions to work against each other. 我认为这是因为一旦隐藏了元素,再次单击触发器就会导致操作相互冲突。

I'm using this W3 exmaple as a reference, the only salient different I notice is that there are different trigger elements for show/hide. 将此 W3示例作为参考,我注意到的唯一显着不同是显示/隐藏有不同的触发元素。

Is it possible to trigger show/hide of an element from the a single div and how can I get this to work? 是否可以从单个div触发元素的显示/隐藏,如何使它起作用?

Because Id is unique for whole document. 因为Id对于整个文档都是唯一的。 try with toggle() 尝试使用toggle()

jQuery("#ptwesv").click(function(){
    jQuery("#ptwest").toggle();
});
jQuery("#ptwesv").click(function(){
    jQuery("#ptwest").toggle();
});

is the way you want. 是您想要的方式。 It toggles the element. 它切换元素。 So if it is shown it hides and the other way around. 因此,如果显示出来,它就会隐藏起来,反之亦然。

At the moment the element will always hide, because of twice the same click element. 目前,由于两次相同的click元素,该元素将始终隐藏。

The toggle() method toggles between hide() and show() for the selected elements. toggle()方法在所选元素的hide()和show()之间切换。

This method checks the selected elements for visibility. 此方法检查所选元素的可见性。 show() is run if an element is hidden. 如果隐藏了元素,则会运行show()。 hide() is run if an element is visible - This creates a toggle effect. 如果元素可见,则运行hide()-这将创建切换效果。

   $("#ptwesv").click(function(){
       $("#ptwest").toggle();
   });

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

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