2

Предположим, у меня есть таблица, которая использует сортировку jquery. Как я могу получить innerHTML строки для обмена с innerHTML другой строки при перетаскивании, а затем сохранить заказ на отправке без использования «.toArray()» или «.serialize()». Например, мне удалось сохранить заказ без использования «.toArray()» или «.serialize()», используя кнопки вверх и вниз для изменения внутреннегоHTML.Как сохранить порядок строк таблицы с помощью сортировки jquery без использования «.toArray()» или «.serialize()»?

jQuery(function() { 
    var ids = []; 
    $("tbody#sortable").sortable({ 
     axis: "y", 
     items: ".row_order", 
     forcePlaceholderSize: true, 
     placeholder: "must-have-class", 
    start: function(event, ui) { 
     //Empty the array to avoid duplication. 
     ids = []; 
     //Store the ids in the array. 
     $.each(event.target.children, function() { 
      ids.push($(this).attr('id')); 
     }); 
    }, 
    update: function(event, ui) { 
     //Store the html in local variables 
     var prevHtml = ui.item.prev().html(); 
     var nextHtml = ui.item.next().html(); 

     //Call .html and pass the html content as an argument 
     ui.item.prev().html(nextHtml); 
     ui.item.next().html(prevHtml); 

     //On an update, loop through the sortable items and reset their items. 
     for (var i = 0; i < event.target.children.length; i++) { 
     $(event.target.children[i]).attr('id', ids[i]); 
     } 
    }   
    }); 
}); 

Это Fiddle

ответ

2

Ваш пример не будет работать, потому что вы присваиваете содержание HTML деталей к переменным и вы не манипулируя элементами DOM в любом случае.

Для того, чтобы обновить внутреннюю HTML, вы должны вызвать .html() по каждому элементу и передать HTML в качестве аргумента:

jQuery(function() { 
    var ids = []; 
    jQuery("#sortable_available").sortable({ 
    items: "li", 
    start: function(event, ui) { 
     //Empty the array to avoid duplication. 
     ids = []; 
     //Store the ids in the array. 
     $.each(event.target.children, function() { 
     ids.push($(this).attr('id')); 
     }) 
    }, 
    update: function(event, ui) { 
     //Store the html in local variables 
     var prevHtml = ui.item.prev().html(); 
     var nextHtml = ui.item.next().html(); 

     //Call .html and pass the html content as an argument 
     ui.item.prev().html(nextHtml); 
     ui.item.next().html(prevHtml); 

     //On an update, loop through the sortable items and reset their items. 
     for (var i = 0; i < event.target.children.length; i++) { 
     $(event.target.children[i]).attr('id', ids[i]); 
     } 
    } 
    }); 
}); 

Там может быть лучшим способом сохранить идентификатор, но выше, является приблизительным примером того, как ваши требования могут быть достигнуты.

Нажмите here для живой демонстрации.

+0

Это потребует более сложной функциональности i e. Подписка на событие запуска и сохранение идентификаторов в переменных. – Yass

+0

Да. Или вы можете сделать внутренний контент сортируемым. Я попробую и немного обновить пример. – Yass

+0

Это был пример, который я сохранил ранее. – Yass

Смежные вопросы