JQuery: Toggle Element that is clicked and hide all other

前端 未结 4 646
别那么骄傲
别那么骄傲 2020-12-02 21:12

I want to hide any visible span elements if any is visible, and toggle it again if a element is clicked


      
4条回答
  •  悲哀的现实
    2020-12-02 21:58

    It can be much simpler than that: Updated Fiddle

    var all_spans = $('.item span').hide();
    
    $('.item a').click(function(e){
        var thisSpan = $(this).parent().find('span'),
            isShowing = thisSpan.is(":visible");
    
        // Hide all spans
        all_spans.hide();
    
        // If our span *wasn't* showing, show it
        if (!isShowing) {
            thisSpan.show();
        }
    
        e.preventDefault();
    });
    

    The main problem with your code was that you were checking whether the a element was visible, rather than checking whether the span was.

    Your code also fell prey to The Horror of Implicit Globals on this line:

    $this = $(this).parent().find('span');
    

    ...which creates a global variable $this because you didn't declare it anywhere.

提交回复
热议问题