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

标签 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 元素的位置并保留其事件吗?

最佳答案

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

而不是使用 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);
        }
    });
}

关于jquery - 替换 DOM 元素的位置并保留其事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9021634/

相关文章:

javascript - 在 .replaceWith() 之后恢复或保留 select 的事件

javascript - 粘性侧边栏行为异常

javascript - 使用 jquery 显示两个数据透视表

javascript - 重置元素后刷新下拉列表

c++ - Qt 中的多线程事件处理程序

android - 按键事件在 Android 设备上不起作用

jquery - 在文件系统上运行的 HTML/Javascript 应用程序、安全问题

c# - KeyPressed 事件调用其他事件

javascript - 用。。。来代替(); jQuery 函数

javascript - 替换为jquery函数