jQuery UI Sortable、更新イベントで現在の場所と新しい場所を決定する方法は?

StackOverflow https://stackoverflow.com/questions/1601827

  •  05-07-2019
  •  | 
  •  

質問

持っている:

<ul id="sortableList">
     <li>item 1</li>
     <li>item 2</li>
     <li>item 3</li>
</ul>

update:function(event、ui){} に接続しましたが、要素の元の位置と新しい位置を取得する方法がわかりません。アイテム3をアイテム1の上に移動する場合、元の位置を 2 (0ベースのインデックス)にし、アイテム3の新しい位置を 0 にします。

役に立ちましたか?

解決

$('#sortable').sortable({
    start: function(e, ui) {
        // creates a temporary attribute on the element with the old index
        $(this).attr('data-previndex', ui.item.index());
    },
    update: function(e, ui) {
        // gets the new and old index then removes the temporary attribute
        var newIndex = ui.item.index();
        var oldIndex = $(this).attr('data-previndex');
        $(this).removeAttr('data-previndex');
    }
});

他のヒント

更新関数が呼び出されたとき、ui.item.sortableは更新されていませんが、UI要素は視覚的に移動しています。
これにより、更新機能で古い位置と新しい位置を取得できます。

   $('#sortable').sortable({    
        update: function(e, ui) {
            // ui.item.sortable is the model but it is not updated until after update
            var oldIndex = ui.item.sortable.index;

            // new Index because the ui.item is the node and the visual element has been reordered
            var newIndex = ui.item.index();
        }    
});

古い位置と新しい位置を確認する方法はいくつかあります。それらを配列に入れます。

$('#sortable').sortable({
    start: function(e, ui) {
        // puts the old positions into array before sorting
        var old_position = $(this).sortable('toArray');
    },
    update: function(event, ui) {
        // grabs the new positions now that we've finished sorting
        var new_position = $(this).sortable('toArray');
    }
});

そして、必要なものを簡単に抽出できます。

同じ問題に対する答えを探していました。フランキーの貢献に基づいて、開始と終了の両方の「注文」を取得することができました。 varを使用した変数スコープで問題が発生したため、ローカル変数ではなく.data()として保存しました:

$(this).data("old_position",$(this).sortable("toArray"))

and

$(this).data("new_position",$(this).sortable("toArray"))

次のように呼び出すことができます(更新/終了関数から):

console.log($(this).data("old_position"))
console.log($(this).data("new_position"))

クレジットはまだフランキーに行きます:)

これは私のために働いた

$('#sortable').sortable({
start: function(e, ui) {
    // puts the old positions into array before sorting
    var old_position = ui.item.index();
},
update: function(event, ui) {
    // grabs the new positions now that we've finished sorting
    var new_position = ui.item.index();
}
});

これは私のために働く、

$('#app').sortable({
    handle: '.handle',

    start: function(evt, ui){
        $(ui.item).data('old-ndex' , ui.item.index());
    },

    update: function(evt, ui) {
        var old_index = $(ui.item).data('old-ndex');
        var new_index = ui.item.index();

        alert('old_index -'+old_index+' new index -'+new_index);

    }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top