0
我目前正在試驗動態加載數據從一個JS對象到HTML容器通過迭代For循環。JavaScript的循環沒有完全遍歷對象
我碰到的牆似乎是因爲For循環不會遍歷整個對象,即使我設置了For循環的高門檻基於計算的內部對象的數量JS對象。
工作解決方案將所有對象加載到它們各自的html容器中。在這一點上,我並不關心在成就屬性對象中顯示對象。
這個實驗是爲了更好的理解純Javascript,所以不需要Jquery或框架建議。
數據對象:
var data = { projects: [{
title: "GET BORN",
tags: ["Live Events", "Stage Design", "Event Promotion", "Music"],
date_started: "21/09/12",
date_finished: "Finish Date",
description: "Music events that explores the underground sound",
achievements: [{milestone:"Launched Brand", date:"datetime", details:"blah"}, {milestone:"Hosted First Night", date:"datetime", details:"moreblah"}, {milestone:"Sold Out Lakota +1000 People", date:"datetime", details:"moreblah"}],
position: 1
}, {
title: "FAIRSTREAM",
tags: ["Web Application", "Trademark", "Music streaming"],
date_started: "10/05/16",
date_finished: "Finish date",
description: "Equal opportunity music streaming application",
achievements: [{milestone:"Launched Brand", date:"datetime", details:"blah"}],
position: 2
}]}
視圖產生功能:
const buildProjectView = (dataSet) => {
const currentProjectIndex = 0
let dataLen = Object.keys(dataSet.projects[currentProjectIndex]).length
// console.log(dataLen)
let objKey = Object.keys(dataSet.projects[currentProjectIndex])
let objValue = Object.values(dataSet.projects[currentProjectIndex])
// console.log(objValue)
for (let i = 0; i < dataLen; i++) {
// console.log("count: " + i)
console.log(objKey[i] + ": " + objValue[i])
let theTitle = document.getElementById(objKey[i])
let content = document.createTextNode(objValue[i])
theTitle.appendChild(content)
}
}
window.onload = buildProjectView(data)
HTML樣板:
<html>
<head>
<title>Mysite Playground</title>
</head>
<body>
<div class="container">
<section class="head">
<h1 id="title"/>
<h2 id="description"/>
<h3 id="date_started"/>
</section>
<section class="body">
<p id="position">#</p>
<p id="achievements"/>
<p id="tags"/>
</section>
</div>
</body>
</html>
我的編碼測試平臺,例如和一些基本樣式: https://codepen.io/wntwrk/pen/bqXYMO
感謝您的幫助提前。
'常量currentProjectIndex = 0 讓DATALEN = Object.keys(dataSet.projects [currentProjectIndex])length' - 這僅處理與'標題對象: 「GET出生了」,'在它和總是返回7。 –