2017-01-05 45 views
2

假設我有一個包含數據的數組,它可能來自Ajax(但不需要在此處執行此操作)。jQuery-UI可排序 - 更新後同步數組(模型)

隨着這陣我產生UL元素的內容,我作出這樣的UL排序,使用jQuery UI的

我想保持與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>

+0

2k聲望在stackoverflow和仍然不使用片段?你應該感到羞愧:) – Dekel

回答

3

代碼進行少許修改,讓你在找什麼:

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>

  1. 而不是創建li內容串 - 我創建li元素,並使用data('d')
  2. 裏面sortable對象的update功能補充說一點的數據 - 我回來從li節點data(根據自己的當前位置 - 這是新訂單)。
+0

謝謝,完美。我還正在研究一些帶有數據ID的東西。那個映射函數正是我需要的 –