【发布时间】:2017-04-11 06:30:57
【问题描述】:
我有一个根据 JSON 数据进行更新的表。 表中的每一行都有一个复选框,其中包含相应 JSON 对象的值,这基本上是关于任何用户的信息。 在选择任何行并保存以在附加到“div.container”的“div.parent”中显示所选用户配置文件时,我还将所选 JSON 对象存储在数组“savedData”中。
现在,我有一些交换按钮,我可以使用它们将每个“div.parent”与下一个或前一个“div.parent”交换。 因此,在交换时,DOM 结构会相应改变。 但是,如何对“savedData”数组进行排序,以匹配交换顺序?例如,对于 DOM 中的第一个“div.parent”,对应的对象应该位于“savedData[0]”。同样,对于 DOM 中的第二个“div.parent”,对应的对象应该位于“savedData[1]”。
我该如何解决这个问题?
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 = new Map; // Keyed by image URL. Start with nothing.
function saveData(){
var errors = [];
// Add selected to map
$('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.get(obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it to the Map:
savedData.set(obj.picture.thumbnail, 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')
)
);
resetEvents();
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
}
function logSavedData(){
// Translate Map to array of values:
var data = Array.from(savedData, function (pair) {
return pair[1];
});
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(data, null, 2));
}
$(document).on('click', '.removeMe', function() {
var key = $('.myLink', $(this).parent()).attr('src');
// Delete this from the saved Data
savedData.delete(key);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
function resetEvents() {
$(".top-btn, .down-btn").unbind('click');
handleEvents();
$('.down-btn').click(function() {
var toMove1 = $(this).parents('.parent');
$(toMove1).insertAfter($(toMove1).next());
handleEvents();
});
$('.top-btn').click(function() {
var toMove1 = $(this).parents('.parent');
$(toMove1).insertBefore($(toMove1).prev());
handleEvents();
});
}
/* 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;
}
<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>
【问题讨论】:
-
这些问题是关于基本的 json 操作
-
这个问题太笼统了。请一次提出一个问题,并提供您尝试过的代码(在这种情况下:为了实现第 6 点),并说明您遇到的具体问题。对于第 8 点,您应该提出一个单独的问题,并提供更多信息和代码,说明您打算如何向用户询问数据,再次提供您尝试实现的代码,以及您遇到的 specific 问题撞到了。
-
很抱歉造成混乱!我现在更新了我的代码和描述。此外,已将问题分开。 stackoverflow.com/questions/43343612/…
标签: jquery arrays json dom dynamic