jQuery-UI 可排序 - 更新后同步数组(模型)

Emm*_*lay 3 javascript arrays jquery jquery-ui

假设我有一个包含数据的数组,它可能来自 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));
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Dek*_*kel 5

代码中的一些更改以获得您正在寻找的内容:

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));
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  1. 而不是将li内容创建为字符串 - 我创建了li元素并使用添加了该点的数据data('d')
  2. 在对象的update函数内部sortable- 我datali节点那里得到了它(基于它们的当前位置 - 这是新的顺序)。