我是JSON和JS的新手,并生成了一个JSON文件,通过.onclick事件显示数据。到目前为止,我已经生成了JSON数据并将其显示在屏幕上,但现在我想以表格格式对其进行样式化,其中元素可以更清晰地看到。任何帮助都会很棒!
这是我的JS:
addEventListener("load", set_up_click_handler);
function set_up_click_handler() {
var url = 'http://localhost/Advanced_Web/Final_Project/data/exhibitions.json';
var button = document.getElementById("button");
button.addEventListener("click", click_handler);
function click_handler(event) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.addEventListener("load", response_handler);
request.send();
};
function response_handler() {
if (this.status == 200) {
var json = this.responseText;
var data = JSON.parse(json);
window.localStorage.setItem('exhibitions', JSON.stringify(data));
var div = document.createElement("div");
div.setAttribute("id", "dateOfExhibition");
var list = $('<ul/>');
for (var item in data) {
list.append(
$("<li />").text(item + ": " + data[item])
);
}
$('#exhibitions').append(list);
} else {
alert('An error has occurred.');
}
}
}
如果今天有人感到额外的慈善事项,我也会遇到以下问题:每次点击我的按钮,列表都会再次出现。如何重新编写代码,使其只显示一次?
答案 0 :(得分:0)
如果没有真正了解所需表格的样式,请参阅示例将数据格式化为带有显示标题的表格,此函数中尚未处理带有空数组的地址
var jsonData = { "id": "Pavlov's Dog", "dateOfExhibition": "2018-07-08T22:00:00.000Z", "address": [], "street": "Bergmannstrasse 29", "city": "Berlin", "country": "Deutschland", "zip": "10473"};
function createTable(jsonData){
//create headers
var head = $("<tr />");
var keys = Object.keys(jsonData);
keys.forEach(function(key){
head.append($("<th>"+ key + "</th>"));
});
$("#exhibitionTable").append(head);
//append data (if you have multiple objects in an array like this wrap this in a forEach)
var row = $("<tr />");
for (var item in jsonData){
row.append($("<td>"+ jsonData[item] + "</td>"));
}
$("#exhibitionTable").append(row);
}
$(document).ready(function(){
createTable(jsonData);
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table id="exhibitionTable">
</table>
</body>
</html>
&#13;