How to toggle elements in and out of DOM using jQuery detach() method?

后端 未结 4 2116
-上瘾入骨i
-上瘾入骨i 2020-12-11 08:29

I have a group of divs arranged in a grid.

To style each div I\'m selecting them with the nth-child() pseudo-class.

div.tile:nth-child(4n-7)         


        
4条回答
  •  星月不相逢
    2020-12-11 08:56

    Everyone was close, but here is exactly what you are looking for with your current html markup: http://jsfiddle.net/vs5o5nLb/2/

    The trick is setting yourself up ahead of time with what you need to actually toggle, then keeping that information around to insert and detach from.

    var $els = $( '.tile' );
    var stack = [];
    var isShown = true;
    
    $els.each(function() {
        var $this = $( this );
        if ( $this.find('.dolphin').length ) {
            stack.push({
                $el : $this,
                index : $els.index( this )
            });
        }
    });
    
    $('.hide-divs').click(function () {
        if ( isShown ) {
            $.each(stack, function() {
                this.$el.detach();
            });
            isShown = false;
        } else {
            $.each(stack, function() {
                $('.tile').eq( this.index ).before( this.$el );
            });
            isShown = true;
        }
    });
    

    I hope it helps.

提交回复
热议问题