nestedSortable 是一个基于 jQuery UI Sortable 的插件,专门用于处理嵌套列表的排序功能。下面我将详细介绍如何从 nestedSortable 获取输出数据。
nestedSortable 允许用户通过拖拽来重新排序嵌套的列表项,并保持父子关系。获取输出通常意味着获取当前列表的层次结构数据,通常以 JSON 格式表示。
toArray
方法这是最常用的方法,可以将嵌套列表转换为一个表示层次结构的数组。
var nestedList = $('#your-list-id').nestedSortable('toArray', {
attribute: 'id', // 使用哪个属性作为标识符
expression: /(.+)/ // 正则表达式匹配ID
});
console.log(nestedList);
// 输出示例: [{id: "item1"}, {id: "item2", children: [{id: "item2-1"}]}]
serialize
方法这个方法会生成一个可以发送到服务器的序列化字符串。
var serialized = $('#your-list-id').nestedSortable('serialize');
console.log(serialized);
// 输出示例: item[]=1&item[]=2&item[2][]=3
如果需要更复杂的输出格式,可以遍历 DOM 元素手动构建数据结构:
function getNestedOutput(list) {
var output = [];
list.children('li').each(function() {
var item = {
id: $(this).attr('id'),
children: getNestedOutput($(this).children('ol, ul'))
};
output.push(item);
});
return output;
}
var customOutput = getNestedOutput($('#your-list-id'));
console.log(customOutput);
原因: 可能没有正确设置 attribute
选项或元素缺少相应的属性
解决: 确保所有列表项都有指定的属性,并正确配置 toArray
方法
原因: DOM 结构可能不符合 nestedSortable 的要求
解决: 确保使用正确的嵌套结构(通常是 <ol>
或 <ul>
包含 <li>
元素)
解决: 考虑分批处理或使用更高效的自定义遍历方法
<!DOCTYPE html>
<html>
<head>
<title>nestedSortable Example</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nestedSortable/2.0.0/jquery.mjs.nestedSortable.min.js"></script>
<style>
ol.sortable, ol.sortable ol { margin: 0 0 0 25px; padding: 0; list-style-type: none; }
ol.sortable li { margin: 5px 0 0 0; padding: 5px; border: 1px solid #ddd; background: #f6f6f6; }
.placeholder { outline: 1px dashed #4183C4; }
</style>
</head>
<body>
<ol class="sortable" id="nested-list">
<li id="item_1">Item 1
<ol>
<li id="item_1_1">Item 1.1</li>
<li id="item_1_2">Item 1.2</li>
</ol>
</li>
<li id="item_2">Item 2</li>
<li id="item_3">Item 3
<ol>
<li id="item_3_1">Item 3.1</li>
<li id="item_3_2">Item 3.2
<ol>
<li id="item_3_2_1">Item 3.2.1</li>
</ol>
</li>
</ol>
</li>
</ol>
<button id="get-output">Get Output</button>
<pre id="output"></pre>
<script>
$(function() {
$('.sortable').nestedSortable({
handle: 'li',
items: 'li',
toleranceElement: '> div',
maxLevels: 5
});
$('#get-output').click(function() {
var output = $('#nested-list').nestedSortable('toArray', {
attribute: 'id'
});
$('#output').text(JSON.stringify(output, null, 2));
});
});
</script>
</body>
</html>
这个示例展示了如何初始化 nestedSortable 以及如何获取和显示当前的嵌套结构。点击"Get Output"按钮将在页面上显示当前的层次结构。