gpt4 book ai didi

javascript - 保存动态创建的 DOM 并创建 JSON

转载 作者:行者123 更新时间:2023-12-03 04:36:21 25 4
gpt4 key购买 nike

我需要帮助来创建动态创建的 dom 对象的 JSON,该对象的格式与接收 JSON 以创建动态元素时的格式完全相同。

请检查下面的 JS Fiddle 链接和源代码。现在,如果您看到了,在表中我正在通过 JSON 获取数据。表中的复选框值是 JSON 对象。当我选择任何复选框并单击“保存”时,就会生成并显示相应的 div。

现在,我想使用“保存显示的数据并创建 json”按钮保存这个动态创建的 DOM 结构,并创建具有相同格式的 JSON(包含所有属性(无论事实如何,是否它们是否显示在相应的父级中。例如,电话号码、图像,所有数据都应该在 JSON 中可用,即使它没有显示但在原始 JSON 中可用)。

JS Fiddle

<!doctype html>
<html>
<head>
<style>
table, th, td {
border: 1px solid #ddd;
border-collapse: collapse;
padding: 10px;
}

table {
margin: auto;
}

.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;
}
</style>
<body>
<button onclick="createTable()">Load Table</button>
<button onclick="saveData()">Save Table data</button>
<table id="datatable" align="center">
<tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>

<br />
<button onclick="createJson()">Save displayed data & create JSON</button>
<br />
<div class="container">
<
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function createTable() {
$.getJSON("https://api.randomuser.me/?results=5", function(data) {
// First, clear the table
$('#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);
});
}

function saveData(){
// Scrape the URLs that were already collected into a Set:
var used = new Set($('.myLink').map(function () {
return $(this).attr('href');
}).get());
var errors = [];
$('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 (used.has(obj.weburl)) {
errors.push(obj.title);
} else {
// Append it to the collection (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>').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>')
)
);
}
// Clear checkbox:
$('input', this).prop('checked', false)
});
if (errors.length)
alert('The following were already selected:\n' + errors.join('\n'))
}
</script>

</body>
</head>
</html>
<小时/>

示例 JSON

{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "romain",
"last": "hoogmoed"
},
"location": {
"street": "1861 jan pieterszoon coenstraat",
"city": "maasdriel",
"state": "zeeland",
"postcode": 69217
},
"email": "romain.hoogmoed@example.com",
"login": {
"username": "lazyduck408",
"password": "jokers",
"salt": "UGtRFz4N",
"md5": "6d83a8c084731ee73eb5f9398b923183",
"sha1": "cb21097d8c430f2716538e365447910d90476f6e",
"sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
},
"dob": "1983-07-14 07:29:45",
"registered": "2010-09-24 02:10:42",
"phone": "(656)-976-4980",
"cell": "(065)-247-9303",
"id": {
"name": "BSN",
"value": "04242023"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/83.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
"nat": "NL"
}
],
"info": {
"seed": "2da87e9305069f1d",
"results": 1,
"page": 1,
"version": "1.1"
}
}

最佳答案

您可以更改代码,以便在每次保存操作时,不仅将数据添加到 div 中,而且还添加到全局变量中,您将在其中添加与您要添加的数据完全相同的数据。包含在复选框的 value 属性中。

然后,在另一个操作中,您只需将其作为 JSON 输出到您需要的任何位置(发布到 URL、保存在 localStorage 中,...)。

下面是代码,其中有一个额外的按钮可以将收集到的项目的 JSON 输出到控制台:

function createTable() {
$.getJSON("https://api.randomuser.me/?results=25", 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')
)
);
})
// 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();
});
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;
}
<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>

关于javascript - 保存动态创建的 DOM 并创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com