【发布时间】:2017-09-06 23:25:15
【问题描述】:
我目前正在尝试通过使用 For 循环对其进行迭代,将数据从 JS 对象动态加载到 html 容器中。
我撞到的墙似乎是因为 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
提前感谢您的帮助。
【问题讨论】:
-
const currentProjectIndex = 0 let dataLen = Object.keys(dataSet.projects[currentProjectIndex]).length- 这只是处理带有title: "GET BORN",的对象,并且总是返回7。
标签: javascript html for-loop iteration javascript-objects