jQuery - move element and return to its exact previous location?

一曲冷凌霜 提交于 2019-12-04 06:32:57

you can clone them, append them , and finally hide the original div, and in return remove the cloned div and show the original.

Below is what I did. Your post leaves out some important details so I'll guess and hopefully they'll apply to your situation.

I'm going to guess you have a click handler on the div.move elements that moves them into the container div.

CSS:

.placeholder { display:none; }

JS:

var id,
    gid = 0;

$('.move').click(function(e){
    if(!$(this).parents('.container')){
        // Move to container
        id = 'placeholder-' + gid++;
        $(this)
            .before('<div class="placeholder ' + id + '"></div>')  // Save a DOM "bookmark"
            .appendTo('.container')                               // Move the element to container
            .data('placeholder', id);                              // Store it's placeholder's info
    }
    else{
        // Move back out of container
        $(this)
            .appendTo('.placeholder.' + $(this).data('placeholder'))  // Move it back to it's proper location
            .unwrap()                               // Remove the placeholder
            .data('placeholder', undefined);        // Unset placeholder data
     }
 });

Your HTML would look like this after clicking on the first div.move:

<div class="container">
    <div class="move>Content</div>
</div>
<ul>
    <li></li>
    <li><div class="placeholder placeholder-0"></div></li>
    <li></li>
    <li><div class="move">Content</div></li>
    <li></li>
</ul>

I have this working, though the above code is untested. Hopefully it conveys the idea. What I like about this approach:

  1. No duplication of elements (which may break unique ID requirements, for example)
  2. Minimal DOM impact
  3. Events and handlers on moved items remain intact but are not duplicated

Is it perfect? No. But it works nicely and is pretty clean. YMMV.

Cheers

Before moving the element, store its .parent() in a variable, then use .append() or .appendTo() to return it when ready.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!