我排除了這樣的前景: 與輸出相關的影像
我想知道的是如何創建這個輸出,而不必<p>使用純 JavaScript 和 JSON 一遍又一遍地撰寫,沒有任何 JS 庫。
JSON 資料如下所示:
[{"id":1,"first_name":"David","food":"Pizza","age":"24"},
{"id":2,"first_name":"Jack","food":"Hamburger","age":"22"},
{"id":3,"first_name":"Harrison","food":"Sweets","age":"8"},.....
我的 HTML 正文如下所示
<body>
</div >
<center>
<p><B>People and their Foods</B></p>
</center>
</div>
</body>
請幫助我,因為我是這個代碼世界的新手。
uj5u.com熱心網友回復:
您可以遍歷資料并在每次迭代時動態創建元素并將它們分配給主/根 div。
// javascript
// pure javascript
// function to render data
function renderData (data) {
var root = document.getElementById("root");
for(var i =0; i<data.length; i ){
// here you can also create inner loop as well. but following is easier for you.
var div = document.createElement("div");
var para1 = document.createElement("P");
para1.innerText = "name:" data[i].first_name;
div.appendChild(para1);
var para2 = document.createElement("P");
para2.innerText = "food:" data[i].food;
div.appendChild(para2);
var para3 = document.createElement("P");
para3.innerText = "age:" data[i].age;
div.appendChild(para3);
root.appendChild(div);
}
}
// load your json data and then call renderData function
var httpRequest = new XMLHttpRequest(); // asynchronous request
httpRequest.open("GET", "local/path/file.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function() {
if (this.readyState === this.DONE) {
// when the request has completed
var object = JSON.parse(this.response);
// assuming that in json file data is an attribute
renderData(object.data);
}
});
<!-- html part -->
<body>
<div class="content">
<center>
<p><b>People and their Foods</b></p>
</center>
<!-- == i have added one div with id root == -->
<div id="root"></div>
</div>
</body>
uj5u.com熱心網友回復:
嘗試如下代碼片段:
const json = [{"id":1,"first_name":"David","food":"Pizza","age":"24"},
{"id":2,"first_name":"Jack","food":"Hamburger","age":"22"},
{"id":3,"first_name":"Harrison","food":"Sweets","age":"8"},]
const content = document.querySelector('.content')
json.forEach(j => {
let div = document.createElement('div')
div.id = j.id
div.style = "margin-bottom: 2em;"
content.appendChild(div)
const divid = content.querySelector(`#${CSS.escape(j.id)}`)
for(let key in j) {
if(key !== 'id') {
let p = document.createElement('p')
let title = ''
key === 'first_name' ? title = 'name' : title = key
p.innerText = title.charAt(0).toUpperCase() title.slice(1) ': ' j[key]
divid.appendChild(p)
}
}
})
<body>
<div class="content">
<h3>People and their Foods</h3>
</div>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321545.html
標籤:javascript html 数组 json
上一篇:C 修改通過引數傳遞的陣列
下一篇:使用指標訪問陣列內的值
