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

后端 未结 4 2094
-上瘾入骨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 09:04

    I suggest still using detach. You can do so with this code:

    var divs;
    
    $('.hide-divs').on('click', function () {
        if(divs) {
            $(divs).appendTo('.row');
            divs = null;
        } else {
            divs = $('.dolphin').parent().detach();
        }
    });
    

    Then to ensure that the same order is used, I came up with this bit of code:

    $('.tile').each(function(i){
        $(this).data('initial-index', i);
    });
    
    ...
    
    $(divs).each(function(){
        var oldIndex = $(this).data('initial-index');
        $('.tile').eq(oldIndex).before(this);
    });
    

    Put it all together and we get this code:

    var divs;
    
    $('.tile').each(function(i){
        $(this).data('initial-index', i);
    });
    
    $('.hide-divs').on('click', function () {
        if(divs) {
            $(divs).appendTo('.row').each(function(){
                var oldIndex = $(this).data('initial-index');
                $('.tile').eq(oldIndex).before(this);
            });
            divs = null;
        } else {
            divs = $('.dolphin').parent().detach();
        }
    });
    

    Demo on jsfiddle: http://jsfiddle.net/tqbzff2v/2/

提交回复
热议问题