我正在编写一个 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/