jQuery UI Sortable, ¿cómo determinar la ubicación actual y la nueva ubicación en el evento de actualización?

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

  •  05-07-2019
  •  | 
  •  

Pregunta

Tengo:

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

He conectado a update: function (event, ui) {} pero no estoy seguro de cómo obtener la posición original y nueva del elemento. Si muevo el elemento 3 por encima del elemento 1, quiero que la posición original sea 2 (índice basado en 0) y que la nueva posición del elemento 3 sea 0 .

¿Fue útil?

Solución

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

Otros consejos

Cuando se invoca la función de actualización, ui.item.sortable no se ha actualizado, sin embargo, el elemento de la interfaz de usuario se ha movido visualmente.
Esto le permite en la función de actualización obtener la posición anterior y la nueva posición.

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

Tienes varias posibilidades para verificar la posición anterior y la nueva. Los pondría en arreglos.

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

Y luego puedes extraer fácilmente lo que necesitas.

Estaba buscando una respuesta al mismo problema. en base a lo que Frankie contribuyó, pude obtener tanto el inicio como el final de "órdenes". Tuve un problema con el alcance de la variable usando la var, así que simplemente los almacené como .data () en lugar de vars locales:

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

y

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

ahora puede llamarlo así (desde las funciones de actualización / finalización):

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

El crédito sigue siendo para Frankie :)

Esto me funcionó

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

Esto funciona para mí,

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

    }
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top