替换DOM元素的位置并保留其事件

时间:2012-01-26 16:38:18

标签: jquery events replacewith

我正在编写一个jquery插件,它获取一个表并允许更改列顺序 将位于oldIndex中的列置于newIndex位置的代码为:

table.find('> thead > tr, > tbody > tr').each(function() {
    var row = $(this);
    var children = row.children();
    var source = $(children[oldIndex ]);
    var destination = $(children[newIndex ]);

    if (oldIndex != newIndex ) {
        destination
            .replaceWith(source)
            .appendTo(row);
    }
});

问题是每个td都有来自此代码之外的事件。使用replaceWith时,会删除这些事件。

任何想法都可以替换DOM元素的位置并保留其事件吗?

2 个答案:

答案 0 :(得分:2)

确保绑定的函数附加到要移动的元素。

我建议使用逻辑交换列,而不是使用replaceWith.eq用于选择特定列的索引,.after().before()用于交换列:

演示:http://jsfiddle.net/SfwXg/

// Indexes are zero-based
var oldIndex = 1;  // = Second column
var newIndex = 2;  // = Third column
var table = $('table');

if (oldIndex != newIndex) {
    if (oldIndex > newIndex) {
        // Let newIndex always be higher than oldIndex
        var tmp = oldIndex;
        oldIndex = newIndex;
        newIndex = oldIndex;
    }
    table.find('> thead > tr, > tbody > tr').each(function() {
//or:table.children('thead,tbody').children().each(function() {
        var row = $(this);
        var children = row.children();

        var right = children.eq(newIndex);
        var left = children.eq(oldIndex);

        children.eq(newIndex).after(left);
        if (newIndex != oldIndex+1) {
           // If they're next to each other, don't swap the columns
           children.eq(oldIndex+1).before(right);
        }
    });
}

答案 1 :(得分:1)

怎么样:

if (oldIndex != newIndex ) {
    var tmp = $('<td>').insertBefore(destination); // create tmp td before destination
    source.after(destination); // move destination after source
    tmp.after(source).remove(); // move source after tmp, remove tmp
}

编辑:上面的代码交换2 td s,这与提出的内容不同(移动单个td)。

无论事件有什么问题,如果您想在source之前移动destination,只需执行source.insertBefore(destination)destination.before(source)。在您的代码中,您将destination移至tr的末尾。

相关问题