2017-04-11 67 views
0

我有一個基於JSON數據更新的表。 表中的每一行都有一個複選框,其中包含相應JSON對象的值,基本上是有關任何用戶的信息。 在選擇任何行並保存以在'div.parent'中顯示所選用戶配置文件並將其附加到'div.container'後,我還將選定的JSON對象存儲在數組'savedData'中。對包含基於DOM結構的對象的動態數組排序

現在,我已經使用了一些交換按鈕,可以將每個「div.parent」與下一個或上一個「div.parent」進行交換。 因此,在交換時,DOM結構相應地發生變化。 但是,如何對'savedData'數組進行排序,以匹配交換順序?例如,對於DOM中的第一個'div.parent',相應的對象應該位於'savedData [0]'。同樣,對於DOM中的第二個「div.parent」,相應的對象應該位於'savedData [1]'。

我該如何解決這個問題?

function createTable() { 
 
\t \t \t $.getJSON("https://api.randomuser.me/?results=5", function(data) { 
 
\t \t \t \t $('#datatable tr:has(td)').remove(); 
 
\t \t \t \t data.results.forEach(function (record) { 
 
\t \t \t \t \t var json = JSON.stringify(record); 
 
\t \t \t \t \t $('#datatable').append(
 
\t \t \t \t \t \t $('<tr>').append(
 
\t \t \t \t \t \t \t $('<td>').append(
 
\t \t \t \t \t \t \t \t $('<input>').attr('type', 'checkbox') 
 
\t \t \t \t \t \t \t \t \t \t \t .addClass('selectRow') 
 
\t \t \t \t \t \t \t \t \t \t \t .val(json) 
 
\t \t \t \t \t \t \t), 
 
\t \t \t \t \t \t \t $('<td>').append(
 
\t \t \t \t \t \t \t \t $('<a>').attr('href', record.picture.thumbnail) 
 
\t \t \t \t \t \t \t \t \t \t .addClass('imgurl') 
 
\t \t \t \t \t \t \t \t \t \t .attr('target', '_blank') 
 
\t \t \t \t \t \t \t \t \t \t .text(record.name.first) 
 
\t \t \t \t \t \t \t), 
 
\t \t \t \t \t \t \t $('<td>').append(record.dob) 
 
\t \t \t \t \t \t) 
 
\t \t \t \t \t); 
 
\t \t \t \t }) 
 
\t \t \t }).fail(function(error) { 
 
\t \t \t \t console.log("**********AJAX ERROR: " + error); 
 
\t \t \t });    
 
\t \t } 
 

 
\t \t var savedData = new Map; // Keyed by image URL. Start with nothing. 
 

 
\t \t function saveData(){ 
 
\t \t \t var errors = []; 
 
\t \t \t // Add selected to map 
 
\t \t \t $('input.selectRow:checked').each(function(count) { 
 
\t \t \t \t // Get the JSON that is stored as value for the checkbox 
 
\t \t \t \t var obj = JSON.parse($(this).val()); 
 
\t \t \t \t // See if this URL was already collected (that's easy with Set) 
 
\t \t \t \t if (savedData.get(obj.picture.thumbnail)) { 
 
\t \t \t \t \t errors.push(obj.name.first); 
 
\t \t \t \t } else { 
 
\t \t \t \t \t // Append it to the Map: 
 
\t \t \t \t \t savedData.set(obj.picture.thumbnail, obj); 
 
\t \t \t \t } 
 
\t \t \t }); 
 
\t \t \t refreshDisplay(); 
 
\t \t \t if (errors.length) { 
 
\t \t \t \t alert('The following were already selected:\n' + errors.join('\n')); 
 
\t \t \t } 
 
\t \t } 
 

 
\t \t function refreshDisplay() { 
 
\t \t \t $('.container').html(''); 
 
\t \t \t savedData.forEach(function (obj) { 
 
\t \t \t \t // Reset container, and append collected data (use jQuery for appending) 
 
\t \t \t \t $('.container').append(
 
\t \t \t \t \t $('<div>').addClass('parent').append(
 
\t \t \t \t \t \t $('<label>').addClass('dataLabel').text('Name: '), 
 
\t \t \t \t \t \t obj.name.first + ' ' + obj.name.last, 
 
\t \t \t \t \t \t $('<br>'), // line-break between name & pic 
 
\t \t \t \t \t \t $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'), 
 
\t \t \t \t \t \t $('<label>').addClass('dataLabel').text('Date of birth: '), 
 
\t \t \t \t \t \t obj.dob, $('<br>'), 
 
\t \t \t \t \t \t $('<label>').addClass('dataLabel').text('Address: '), $('<br>'), 
 
\t \t \t \t \t \t obj.location.street, $('<br>'), 
 
\t \t \t \t \t \t obj.location.city + ' ' + obj.location.postcode, $('<br>'), 
 
\t \t \t \t \t \t obj.location.state, $('<br>'), 
 
\t \t \t \t \t \t $('<button>').addClass('removeMe').text('Delete'), 
 
\t \t \t \t \t \t $('<button>').addClass('top-btn').text('Swap with top'), 
 
\t \t \t \t \t \t $('<button>').addClass('down-btn').text('Swap with down') 
 
\t \t \t \t \t) \t 
 
\t \t \t \t); 
 
\t \t \t \t resetEvents(); 
 
\t \t \t }) 
 
\t \t \t // Clear checkboxes: 
 
\t \t \t $('.selectRow').prop('checked', false); 
 
\t \t } 
 

 
\t \t function logSavedData(){ 
 
\t \t \t // Translate Map to array of values: 
 
\t \t \t var data = Array.from(savedData, function (pair) { 
 
\t \t \t \t return pair[1]; 
 
\t \t \t }); 
 
\t \t \t // Convert to JSON and log to console. You would instead post it 
 
\t \t \t // to some URL, or save it to localStorage. 
 
\t \t \t console.log(JSON.stringify(data, null, 2)); 
 
\t \t } 
 

 
\t \t $(document).on('click', '.removeMe', function() { 
 
\t \t \t var key = $('.myLink', $(this).parent()).attr('src'); 
 
\t \t \t // Delete this from the saved Data 
 
\t \t \t savedData.delete(key); 
 
\t \t \t // And redisplay 
 
\t \t \t refreshDisplay(); 
 
\t \t }); 
 
\t \t 
 
\t \t \t /* Swapping the displayed articles in the result list */ 
 
\t \t \t function resetEvents() { 
 

 
\t \t \t \t $(".top-btn, .down-btn").unbind('click'); 
 

 
\t \t \t \t handleEvents(); 
 
\t \t \t \t 
 
\t \t \t \t $('.down-btn').click(function() { 
 
\t \t \t \t \t var toMove1 = $(this).parents('.parent'); 
 

 
\t \t \t \t \t $(toMove1).insertAfter($(toMove1).next()); 
 

 
\t \t \t \t \t handleEvents(); 
 
\t \t \t \t }); 
 

 
\t \t \t \t $('.top-btn').click(function() { 
 
\t \t \t \t \t var toMove1 = $(this).parents('.parent'); 
 
\t \t \t \t \t 
 
\t \t \t \t \t $(toMove1).insertBefore($(toMove1).prev()); 
 
\t \t \t \t \t handleEvents(); 
 
\t \t \t \t }); 
 

 
\t \t \t } 
 
\t \t \t \t 
 
\t \t \t /* Disable top & down buttons for the first and the last article respectively in the result list */ 
 
\t \t \t function handleEvents() { 
 
\t \t \t \t $(".top-btn, .down-btn").prop("disabled", false).show(); 
 

 
\t \t \t \t $(".parent:first").find(".top-btn").prop("disabled", true).hide(); 
 

 
\t \t \t \t $(".parent:last").find(".down-btn").prop("disabled", true).hide(); 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t $(document).ready(function(){ 
 
\t \t \t \t $('#showExtForm-btn').click(function(){ 
 
\t \t \t \t \t $('#extUser').toggle(); 
 
\t \t \t \t }); 
 
\t \t \t \t $("#extArticleForm").submit(function(){ 
 

 
        addExtUser(); 
 
        return false; 
 
       }); 
 
\t \t \t });
table, th, td { 
 
\t \t \t border: 1px solid #ddd; 
 
\t \t \t border-collapse: collapse; 
 
\t \t \t padding: 10px; 
 
\t \t } 
 

 
\t \t .parent { 
 
\t \t \t height: 25%; 
 
\t \t \t width: 90%; 
 
\t \t \t padding: 1%; 
 
\t \t \t margin-left: 1%; 
 
\t \t \t margin-top: 1%; 
 
\t \t \t border: 1px solid black; 
 

 
\t \t } 
 

 
\t \t .parent:nth-child(odd){ 
 
\t \t \t background: skyblue; 
 
\t \t } 
 

 
\t \t .parent:nth-child(even){ 
 
\t \t \t background: green; 
 
\t \t } 
 
\t \t 
 
\t \t label { 
 
\t \t \t float: left; 
 
\t \t \t width: 80px; 
 
\t \t } 
 
\t \t input { 
 
\t \t \t width: 130px; 
 
\t \t }
<button onclick="createTable()">Create Table</button> 
 
\t \t <table id="datatable"> 
 
\t \t \t <tr><th>Select</th><th>Name</th><th>DOB</th></tr> 
 
\t \t </table> 
 
\t \t <button onclick="saveData()">Save Selected</button> 
 
\t \t <br /> 
 
\t \t <div class="container"></div> 
 
\t \t <button onclick="logSavedData()">Get Saved Data</button>

+0

這些問題是關於基本JSON操縱 – madalinivascu

+0

這個問題太廣。請一次提出一個問題,並提供您嘗試過的代碼(在這種情況下:爲達到第6點),指定您碰到的具體問題。對於第8點,您應該提出一個單獨的問題,並提供更多關於如何向用戶詢問數據的信息和代碼,再次提供您嘗試實現的代碼以及碰到的* specific *問題。 – trincot

+0

抱歉有關混淆!我現在更新了我的代碼和說明。此外,分離了問題。 http://stackoverflow.com/questions/43343612/add-external-object-to-an-existing-array – Sunny

回答

1

在你想保持特定順序的情況下Map是不太適合。在這種情況下,使用標準數組。這樣做的好處還在於,該數組正是您想要導出爲JSON的內容。缺點是您需要遍歷該數組以查看是否已包含一個元素(例如,使用find)。

事件處理程序復位你可以使用事件委託,就像你已經有它的刪除操作(與$(document).on語法簡單地避免。

我建議不執行父div的交換直接,但將它們應用到savedData陣列,然後用refreshDisplay函數來顯示從該陣列的結果

參見下面的代碼段:

function createTable() { 
 
    $.getJSON("https://api.randomuser.me/?results=5", function(data) { 
 
     $('#datatable tr:has(td)').remove(); 
 
     data.results.forEach(function (record) { 
 
      var json = JSON.stringify(record); 
 
      $('#datatable').append(
 
       $('<tr>').append(
 
        $('<td>').append(
 
         $('<input>').attr('type', 'checkbox') 
 
            .addClass('selectRow') 
 
            .val(json) 
 
        ), 
 
        $('<td>').append(
 
         $('<a>').attr('href', record.picture.thumbnail) 
 
           .addClass('imgurl') 
 
           .attr('target', '_blank') 
 
           .text(record.name.first) 
 
        ), 
 
        $('<td>').append(record.dob) 
 
       ) 
 
      ); 
 
     }) 
 
    }).fail(function(error) { 
 
     console.log("**********AJAX ERROR: " + error); 
 
    });    
 
} 
 

 
var savedData = []; // The objects as array, so to have an order. 
 

 
function saveData(){ 
 
    var errors = []; 
 
    // Add selected to array 
 
    $('input.selectRow:checked').each(function(count) { 
 
     // Get the JSON that is stored as value for the checkbox 
 
     var obj = JSON.parse($(this).val()); 
 
     // See if this URL was already collected (that's easy with Set) 
 
     if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) { 
 
      errors.push(obj.name.first); 
 
     } else { 
 
      // Append it 
 
      savedData.push(obj); 
 
     } 
 
    }); 
 
    refreshDisplay(); 
 
    if (errors.length) { 
 
     alert('The following were already selected:\n' + errors.join('\n')); 
 
    } 
 
} 
 

 
function refreshDisplay() { 
 
    $('.container').html(''); 
 
    savedData.forEach(function (obj) { 
 
     // Reset container, and append collected data (use jQuery for appending) 
 
     $('.container').append(
 
      $('<div>').addClass('parent').append(
 
       $('<label>').addClass('dataLabel').text('Name: '), 
 
       obj.name.first + ' ' + obj.name.last, 
 
       $('<br>'), // line-break between name & pic 
 
       $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'), 
 
       $('<label>').addClass('dataLabel').text('Date of birth: '), 
 
       obj.dob, $('<br>'), 
 
       $('<label>').addClass('dataLabel').text('Address: '), $('<br>'), 
 
       obj.location.street, $('<br>'), 
 
       obj.location.city + ' ' + obj.location.postcode, $('<br>'), 
 
       obj.location.state, $('<br>'), 
 
       $('<button>').addClass('removeMe').text('Delete'), 
 
       $('<button>').addClass('top-btn').text('Swap with top'), 
 
       $('<button>').addClass('down-btn').text('Swap with down') 
 
      ) \t 
 
     ); 
 
    }) 
 
    // Clear checkboxes: 
 
    $('.selectRow').prop('checked', false); 
 
    handleEvents(); 
 
} 
 

 
function logSavedData(){ 
 
    // Convert to JSON and log to console. You would instead post it 
 
    // to some URL, or save it to localStorage. 
 
    console.log(JSON.stringify(savedData, null, 2)); 
 
} 
 

 
function getIndex(elem) { 
 
    return $(elem).parent('.parent').index(); 
 
} 
 

 
$(document).on('click', '.removeMe', function() { 
 
    // Delete this from the saved Data 
 
    savedData.splice(getIndex(this), 1); 
 
    // And redisplay 
 
    refreshDisplay(); 
 
}); 
 

 
/* Swapping the displayed articles in the result list */ 
 
$(document).on('click', ".down-btn", function() { 
 
    var index = getIndex(this); 
 
    // Swap in memory 
 
    savedData.splice(index, 2, savedData[index+1], savedData[index]); 
 
    // And redisplay 
 
    refreshDisplay(); 
 
}); 
 

 
$(document).on('click', ".top-btn", function() { 
 
    var index = getIndex(this); 
 
    // Swap in memory 
 
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]); 
 
    // And redisplay 
 
    refreshDisplay(); 
 
}); 
 
    
 
/* Disable top & down buttons for the first and the last article respectively in the result list */ 
 
function handleEvents() { 
 
    $(".top-btn, .down-btn").prop("disabled", false).show(); 
 
    $(".parent:first").find(".top-btn").prop("disabled", true).hide(); 
 
    $(".parent:last").find(".down-btn").prop("disabled", true).hide(); 
 
} 
 

 
$(document).ready(function(){ 
 
    $('#showExtForm-btn').click(function(){ 
 
     $('#extUser').toggle(); 
 
    }); 
 
    $("#extArticleForm").submit(function(){ 
 
     addExtUser(); 
 
     return false; 
 
    }); 
 
});
table, th, td { 
 
    border: 1px solid #ddd; 
 
    border-collapse: collapse; 
 
    padding: 10px; 
 
} 
 

 
.parent { 
 
    height: 25%; 
 
    width: 90%; 
 
    padding: 1%; 
 
    margin-left: 1%; 
 
    margin-top: 1%; 
 
    border: 1px solid black; 
 

 
} 
 

 
.parent:nth-child(odd){ 
 
    background: skyblue; 
 
} 
 

 
.parent:nth-child(even){ 
 
    background: green; 
 
} 
 

 
label { 
 
    float: left; 
 
    width: 80px; 
 
} 
 
input { 
 
    width: 130px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button onclick="createTable()">Create Table</button> 
 
<table id="datatable"> 
 
    <tr><th>Select</th><th>Name</th><th>DOB</th></tr> 
 
</table> 
 
<button onclick="saveData()">Save Selected</button> 
 
<br /> 
 
<div class="container"></div> 
 
<button onclick="logSavedData()">Get Saved Data</button>

+0

太棒了!非常感謝您的幫助! – Sunny