假设我有一个包含数据的数组,它可能来自 Ajax(但无需在此处执行此操作)。
使用该数组,我生成 UL 元素的内容,并使用 jQuery-UI 使 UL 可排序
在客户端对它进行排序之后,我希望保持数组的顺序与 UL 同步。
有没有一种优雅的方法来做到这一点?
var locations = [
{name: 'point 0', location: [50.8674162,4.3772933]},
{name: 'point 1', location: [50.8135113,4.3247394]},
{name: 'point 2', location: [50.8771732,4.3544551]},
{name: 'point 3', location: [50.8460485,4.3664706]}
];
function generateUl() {
var content = '';
for(var i in locations) {
content += '<li>'+ locations[i].name +' ('+ locations[i].location.toString() +')</li>';
}
$('#points').html(content);
}
$(document).ready(function() {
generateUl();
$('#points').sortable({
update: function(event, ui) {
//$('#points li').each( function(e) {
//});
// so, I would like to see this display change after every update and have the order match
$('#display').html(JSON.stringify(locations));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<ul id="points"></ul>
<div id="display"></div>
对代码进行一些更改以获得您正在寻找的内容:
var locations = [
{name: 'point 0', location: [50.8674162,4.3772933]},
{name: 'point 1', location: [50.8135113,4.3247394]},
{name: 'point 2', location: [50.8771732,4.3544551]},
{name: 'point 3', location: [50.8460485,4.3664706]}
];
function generateUl() {
for(var i in locations) {
li = $('<li>'+ locations[i].name +' ('+ locations[i].location.toString() +')</li>');
li.data('d', locations[i])
$('#points').append(li);
}
}
$(document).ready(function() {
generateUl();
$('#points').sortable({
update: function(event, ui) {
new_locations = $(this).find('li').map(function(i, el) {
return $(el).data('d')
}).get()
$('#display').html(JSON.stringify(new_locations));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<ul id="points"></ul>
<div id="display"></div>
- 而不是创建
li
内容为字符串 - 我创建的li
元素并使用添加该点的数据data('d')
- 在 - 的里面
update
的功能sortable
对象 - 我回来了data
来自li
节点(基于它们当前的位置 - 这是新的顺序)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)