JQuery: Toggle Element that is clicked and hide all other

前端 未结 4 644
别那么骄傲
别那么骄傲 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:56

     $('.item span').hide();
    
    $('.item a').click(function(e){
    
        e.preventDefault();
        // hide all span
        var $this = $(this).parent().find('span');
        $(".item span").not($this).hide();
    
        // here is what I want to do
        $this.toggle();
    
    });
    

    Check demo

    Update with explanation:

    The problem is when you hide all spans, you also hide the current span => all spans have the same state (hidden), and your next line display it again. You have to exclude the current element when hiding and use toggle method to toggle its state (simpler than using if to check)

    Another problem is try to avoid implicit global by using var to declare $this:

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

提交回复
热议问题