Подтвердить что ты не робот

JQuery UI Sortable, как определить текущее местоположение и новое местоположение в событии обновления?

У меня есть:

<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.

4b9b3361

Ответ 1

$('#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');
    }
});

Ответ 2

При вызове функции обновления ui.item.sortable не обновляется, однако элемент пользовательского интерфейса визуально перемещается.
Это позволяет вам в функции обновления получать старую позицию и новую позицию.

   $('#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();
        }    
});

Ответ 3

У вас есть несколько возможностей проверить старую и новую позицию. Я бы поставил их в массивы.

$('#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');
    }
});

И тогда вы можете легко извлечь то, что вам нужно.

Ответ 4

Я искал ответ на тот же вопрос. основанный на том, что внес Фрэнки, я смог получить как начальные, так и конечные "заказы". У меня была проблема с переменной областью с использованием var, поэтому я просто сохранил их как .data() вместо локальных vars:

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

и

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

теперь вы можете вызвать его так (из функций обновления/завершения):

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

Кредит все еще идет к Фрэнки:)

Ответ 5

Это сработало для меня

$('#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();
}
});

Ответ 6

Это работает для меня,

$('#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);

    }
});