3

テーブルを取得して列の順序を変更できる 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 要素の位置を置き換えて、そのイベントを保持できるアイデアはありますか?

4

2 に答える 2

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);
        }
    });
}
于 2012-01-26T16:50:27.600 に答える
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
}

EDIT : 上記のコードは 2 つtdの s を交換します。これは、要求されたものとは異なります (単一の を移動しtdます)。

sourceイベントの問題に関係なく、 の前に移動したい場合はdestination、単にsource.insertBefore(destination)、またはを実行しdestination.before(source)ます。あなたのコードdestinationでは、の最後に移動していますtr

于 2012-01-26T16:45:39.437 に答える