2017-04-11 40 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