假设我有一个使用 jquery 可排序的表。如何在拖动时让一行的innerHTML与另一行的innerHTML交换,然后在提交时保存订单而不使用“.toArray()”或“.serialize()”。例如,我成功地通过使用向上和向下按钮交换innerHTML来保存订单,而无需使用“.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
最佳答案
您的示例将不起作用,因为您将项目的 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]);
}
}
});
});
可能有更好的方法来维护 ids,但上面是如何实现您的要求的一个粗略示例。
点击here 进行现场演示。
关于jquery - 如何使用 jquery sortable 保存表行的顺序而不使用 ".toArray()"或 ".serialize()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36341973/