jQuery-UI可排序 – 更新后同步数组(模型)
假设我有一个包含数据的数组,它可能来自Ajax(但这里不需要这样做)。
使用该数组我生成UL元素的内容,我使用jQuery-UI使UL可排序
在客户端对其进行排序之后,我想保持arrays的顺序与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 += ''+ locations[i].name +' ('+ locations[i].location.toString() +') '; } $('#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)); } }); });
在代码中进行一些更改以获得您正在寻找的内容:
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 = $(''+ locations[i].name +' ('+ locations[i].location.toString() +') '); 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)); } }); });