我使用了来自Sortable items and subitems in list on jQuery ui sortable的解决方案,所有内容都应该按照它应该排序,我唯一不明白该怎么做的是将它们序列化,以便我可以相应地修改数据库。
https://jsfiddle.net/5zwgx45q/
我根本不了解jQuery或JavaScript,所以这对我来说都是丛林。
我使用以下代码来实现我想要的其他功能。
$(document).ready(function() {
var data;
// Sort the parents
$(".sortProducts").sortable({
containment: "document"
, group: 'serialization'
, items: "> div"
, handle: ".move"
, tolerance: "pointer"
, cursor: "move"
, opacity: 0.5
, revert: 300
, placeholder: "productPlaceholder"
, start: function(e, ui) {
ui.placeholder.height(ui.helper.outerHeight());
}
, stop: function(event, ui) {
data = $(".sortProducts").sortable("toArray", {
attribute: 'data-id'
});
}
});
$("#saveOrder").click(function() {
$.ajax({
url: 'process/sortMenu.php?action=products'
, type: 'POST'
, dataType: 'json'
, data: {
newOrder: JSON.stringify(data)
},
success: function(output) {
alert('Menu order changed successfully!');
},
error: function(output) {
alert($(output['responseText']).text());
}
});
});
})
它序列化所有内容
data = $(".sortProducts").sortable("toArray", {attribute: 'data-id'});
我可以将更改应用于数据库。这里的区别在于我有两组可排序的(父母和孩子),所以我不知道如何使序列化适用于两者以及如何使用它。
孩子们可以在父母之间移动,我需要能够在数据库中反映出来。所以我不知何故需要知道哪个孩子属于父母。
数据存储在数据库中,就像论坛一样。
ID | MenuID | Name | Position
-----------------------------
1 | 0 | Nme1 | 1
2 | 1 | Nme2 | 2
3 | 1 | Nme3 | 3
4 | 0 | Nme4 | 4
如果MenuID为0,则它是父级。如果MenuID为1,则它的父级是ID = 1的项目。
答案 0 :(得分:1)
你可以这样做:
function getSortableList(className){
var sortables = $(className);
var myArray = new Array();
sortables.each(function() {
myArray = myArray.concat($(this).sortable('toArray'));
})
// Show length of array
alert(myArray.length);
}
修改强>
根据您的数据库表转换项目,您可以使用以下代码:
function createRecordsFromSortableList() {
var sortables = $(".menuItems");
var records = [];
sortables.each(function() {
var currentParent = this;
var myRecord = new record($(this).attr("id"), "0", $(this).closest(".menuGroup").find('h2').text());
records.push(myRecord);
$(this).find('.menuItem').each(function() {
var myRecord = new record($(this).attr("id"), $(currentParent).attr("id"),$.trim($(this).text().replace(/[\t\n]+/g,' ')));
records.push(myRecord);
});
});
alert("Please see records in console.");
console.log(records);
}
function record(id, menuId, name) {
this.id = id;
this.menuId = menuId;
this.name = name;
}