替换 DOM 元素的位置并保留其事件
我正在编写一个 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 元素的位置并保留其事件吗?
I am writing a jquery plugin that gets a table and allow to change the columns order.
The code for putting the column that in position oldIndex in position newIndex is:
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);
}
});
The problem is that each td has events that came outside this code. When using replaceWith
, it removes those events.
Any idea hoe can I replace position of DOM element and preserve its events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保绑定函数附加到要移动的元素。
我建议使用逻辑来交换列,而不是使用
replaceWith
。.eq
用于选择特定列的索引,< a href="http://api.jquery.com/after/" rel="nofollow noreferrer">.after()
和.before()
用于交换列:演示: http://jsfiddle.net/SfwXg/
Make sure that the bound functions are attached to the to-be-moved element.
Instead of using
replaceWith
, I suggest to use logic to swap the columns..eq
is used to select the index of a specific column,.after()
and.before()
are used to swap the columns:Demo: http://jsfiddle.net/SfwXg/
怎么样:
编辑:上面的代码交换了 2 个
td
,这与所要求的不同(移动一个td
)。无论事件有什么问题,如果您想将
source
移动到destination
之前,只需执行source.insertBefore(destination)
或目的地.之前(源)
。在您的代码中,您将destination
移动到tr
的末尾。How about:
EDIT: the code above swaps 2
td
s, which is different that what was asked (move a singletd
).Regardless of the problem with events, if you want to move
source
beforedestination
, simply dosource.insertBefore(destination)
, ordestination.before(source)
. In your code you're movingdestination
to the end of thetr
.