📅  最后修改于: 2023-12-03 15:32:10.474000             🧑  作者: Mango
jQuery UI Sortable 是一款强大的 jQuery 插件,用于实现可排序样式的列表。然而,在实现排序时,有时会遇到需求,需要恢复最初的顺序。本文将介绍如何实现这一需求。
var order = $("#sortable").sortable("toArray");
$("#sortable").append(
$.map(order, function(val) {
return $("#" + val)[0];
})
);
$("#sortable").sortable("refresh");
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery UI Sortable 恢复选项</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
#sortable li { margin: 3px 3px 3px 0; padding: 1px; float: left; width: 96%; height: auto; }
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function() {
$("#sortable").sortable({
placeholder: "ui-state-highlight",
update: function() {
var order = $(this).sortable("toArray");
console.log(order); // 记录下顺序
}
});
$("#sort-order").click(function() {
var order = ["item1", "item2", "item3", "item4", "item5"]; // 假设记录的顺序
$("#sortable").append(
$.map(order, function(val) {
return $("#" + val)[0];
})
);
$("#sortable").sortable("refresh"); // 更新列表
});
$("#reset-order").click(function() {
$("#sortable").html("<li id='item1' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Item 1</li><li id='item2' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Item 2</li><li id='item3' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Item 3</li><li id='item4' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Item 4</li><li id='item5' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>Item 5</li>");
$("#sortable").sortable("refresh"); // 更新列表
});
$("ul, li").disableSelection();
});
</script>
</head>
<body>
<ul id="sortable">
<li id="item1" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
<li id="item2" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
<li id="item3" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
<li id="item4" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
<li id="item5" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li>
</ul>
<button id="sort-order">Restore Order</button>
<button id="reset-order">Reset Order</button>
</body>
</html>