交换2个html元素并保留事件监听器 [英] Swap 2 html elements and preserve event listeners on them

查看:164
本文介绍了交换2个html元素并保留事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有类似的问题,但是所有的答案都是用于交换内容中的html元素。

There are similar questions, but all the answers are for swapping html elements only for the content inside.

我需要交换两个具有大量内容的div ,选择框,输入等)与元素上的事件监听器等。不破坏所有这些。

I need to swap two divs with lots of content(tables, select boxes, inputs and so on) with event listeners on the elements etc. Without destroying all that.

我可以访问jQuery 1.5。所以答案是可以的。

I have access of jQuery 1.5. So answers with it are OK.

推荐答案

要交换两个div,而不会丢失事件处理程序或破坏DOM引用,您只需移动它们在DOM中。关键是不要改变innerHTML,因为它会从头开始重新创建新的DOM节点,并且丢失那些DOM对象上的所有先前的事件处理程序。

To swap two divs without losing event handlers or breaking DOM references, you can just move them in the DOM. The key is NOT to change the innerHTML because that recreates new DOM nodes from scratch and all prior event handlers on those DOM objects are lost.

但是,如果你只是移动DOM元素到DOM中的一个新地方,所有事件都保持附加,因为DOM元素只能在不改变DOM元素的情况下被重新定位。

But, if you just move the DOM elements to a new place in the DOM, all events stay attached because the DOM elements are only reparented without changing the DOM elements themselves.

这是一个快速的函数,可以交换DOM中的两个元素。只要一个不是另一个元素,它应该与任何两个元素一起工作:

Here's a quick function that would swap two elements in the DOM. It should work with any two elements as long as one is not a child of the other:

function swapElements(obj1, obj2) {
    // create marker element and insert it where obj1 is
    var temp = document.createElement("div");
    obj1.parentNode.insertBefore(temp, obj1);

    // move obj1 to right before obj2
    obj2.parentNode.insertBefore(obj1, obj2);

    // move obj2 to right before where obj1 used to be
    temp.parentNode.insertBefore(obj2, temp);

    // remove temporary marker node
    temp.parentNode.removeChild(temp);
}

你可以在这里看到它: http://jsfiddle.net/jfriend00/NThjN/

You can see it work here: http://jsfiddle.net/jfriend00/NThjN/

这里是一个没有插入临时元素的版本:

And here's a version that works without the temporary element inserted:

function swapElements(obj1, obj2) {
    // save the location of obj2
    var parent2 = obj2.parentNode;
    var next2 = obj2.nextSibling;
    // special case for obj1 is the next sibling of obj2
    if (next2 === obj1) {
        // just put obj1 before obj2
        parent2.insertBefore(obj1, obj2);
    } else {
        // insert obj2 right before obj1
        obj1.parentNode.insertBefore(obj2, obj1);

        // now insert obj1 where obj2 was
        if (next2) {
            // if there was an element after obj2, then insert obj1 right before that
            parent2.insertBefore(obj1, next2);
        } else {
            // otherwise, just append as last child
            parent2.appendChild(obj1);
        }
    }
}

工作演示: http://jsfiddle.net/jfriend00/oq92jqrb/

这篇关于交换2个html元素并保留事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆