Re-attaching jQuery detach();

后端 未结 8 1188
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 01:42

I have detached a div and want to re-attach it when clicking on a button.

Here\'s the code:

$(\'#wrapper\').detach();

$(\"#open_menu\").click(functi         


        
相关标签:
8条回答
  • 2020-12-09 02:42

    if you want your item to attach at the beginning of the element you could use .prepend()

    otherwise you could attach it using append().

    in your case it would be:

    var $wrapper = $('#wrapper').detach();
    
    $("#open_menu").click(function(){
        //ATTACH HERE !!!
        $(this).prepend($wrapper); // or $(this).append($wrapper);
    });
    

    I hope it helps :)

    0 讨论(0)
  • 2020-12-09 02:46

    I needed a solution that would work even if there are other elements after the target element to detach and then reattach. This means that append may not be reliable because it would move that element back to the end of its parent. I had to use a placeholder which may not be the most elegant solution, but I haven't found another way..

    var $wrapper = $('#wrapper')
        , $placeholder = $('<span style="display: none;" />')
            .insertAfter( $wrapper )
        ;
    $wrapper.detach();
    
    $("#open_menu").on('click',function(){
        $wrapper.insertBefore( $placeholder );
        $placeholder.remove();
    });
    

    To make this more reusable, it might be better to wrap it in a jQuery plugin:

    (function($){
    
        $.fn.detachTemp = function() {
            this.data('dt_placeholder',$('<span style="display: none;" />')
                .insertAfter( this ));
            return this.detach();
        }
    
        $.fn.reattach = function() {
            if(this.data('dt_placeholder')){
                this.insertBefore( this.data('dt_placeholder') );
                this.data('dt_placeholder').remove();
                this.removeData('dt_placeholder');
            }
            else if(window.console && console.error)
            console.error("Unable to reattach this element because its placeholder is not available.");
            return this;
        }
    
    })(jQuery);
    

    Usage:

    var $wrapper = $('#wrapper').detachTemp();
    $("#open_menu").on('click',function(){
        $wrapper.reattach();
    });
    
    0 讨论(0)
提交回复
热议问题