【发布时间】:2018-03-19 19:21:57
【问题描述】:
我无法将这 2 个 JSON 对象显示到 DOM。我要:
A) 为 2 个不同的人编写一个 JSON 对象数组,其中包括多个键/值和
B) 遍历对象数组。创建一个 2-col 页面,在一侧显示第一个人详细信息,在另一侧显示第二个人详细信息。
我相信我是使用 jQuery 将对象显示到浏览器窗口,但我不知道如何完成这项任务。因此,经过很长时间在“谷歌”上寻找答案并尝试了很多尝试和所有错误。我请求那些比我了解更多(不是很难)的人提供一些帮助。谢谢。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head
content must come *after* these tags -->
<title>Iterate Through JSON Array Object</title>
<!-- Bootstrap -->
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media
queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js">
</script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js">
</script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6" id="div0">
<h1>Column 1</h1>
</div>
<div class="col-sm-6" id="div1">
<h1>Column 2</h1>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://sabioapi2.azurewebsites.net/scripts/sabio.js"></script>
<!-- All your code goes below here-->
<script type="text/javascript">
myObj = {
"people": [
{
"firstName": "Juana"
, "lastName": "Doe"
, "age": 23
, "streetAddress": "123 Main St."
, "city": "Culver City"
, "state": "CA"
, "zip": 92340
},
{
"firstName": "Juan"
, "lastName": "Doe"
, "age": 47
, "streetAddress": "123 Main St."
, "city": "Culver City"
, "state": "CA"
, "zip": 92340
}
]
}
for (var i = 0; i < myObj.people.length; i++) {
$("#div" + i).append("<h1>" + i + ": " + myObj.people[i] + "</h1>");
//document.getElementById("div" + i).innerHTML += i + ": " +
myObj[i] + "<br>";
//console.log(myObj.people[i]);
}
</script>
*
【问题讨论】:
-
你能告诉我们你期望的输出是什么吗?
-
它应该遍历两个数组并在浏览器/DOM 中显示它们(键/值)。两列,每列一个数组。
标签: javascript jquery arrays json object