Toggle show/hide (jQuery)

时间:2017-07-10 15:20:04

标签: javascript 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;

and another div containing the content I want to show hide with the ID #ptwest.

The jQuery I'm using is this:

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

Is it possible to trigger show/hide of an element from the a single div and how can I get this to work?

3 个答案:

答案 0 :(得分:3)

Because Id is unique for whole document. try with toggle()

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

答案 1 :(得分:2)

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.

答案 2 :(得分:0)

The toggle() method toggles between hide() and show() for the selected elements.

This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

   $("#ptwesv").click(function(){
       $("#ptwest").toggle();
   });
相关问题