显示JavaScript对象的列表作为HTML列表项目 [英] Displaying List Of JavaScript Objects As HTML List Items
本文介绍了显示JavaScript对象的列表作为HTML列表项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试这个时,HMTL页面只显示最后一个对象,而不是所有的对象。
这是我的JavaScript文件
var family = {
aaron:{
name:'Aaron',
age:30
},
megan:{
name:'Megan',
age :40
},
aaliyah:{
name:'Aaliyah',
age:2
}
}
var list = function(family){
for(var prop in family){
var elList = document.getElementById('aaron-family')。innerHTML = prop;
}
}
列表(家庭);
这里是我的HTML文件
< HTML>
< head>
< title>亚伦的对象测试< / title>
< / head>
< li id =aaron-family>嘿,这是它去的地方< / li>
< footer>
< script src =objects.js>< / script>
< / footer>
< / html>
解决方案
< li>
没有父母< ol>
或< ul> / code>标签,等等)...但我会说主要的错误是,你将每个后续输出与每个任务分配
innerHTML
。解决方案:将编译数组赋给 innerHTML
(使用 join
$ b
var list = function(family){
var names = [] ;
for(var prop in family){
names.push(prop.name);
}
document.getElementById('aaron-family')。innerHTML = names.join('');
}
list(family);
When I attempt this, the HMTL page only displays the last object, instead of all the objects.
Here is my JavaScript file
var family = {
aaron: {
name: 'Aaron',
age: 30
},
megan: {
name: 'Megan',
age: 40
},
aaliyah: {
name: 'Aaliyah',
age: 2
}
}
var list = function(family) {
for (var prop in family) {
var elList = document.getElementById('aaron-family').innerHTML = prop;
}
}
list(family);
And here's my HTML file
<html>
<head>
<title>Aaron's Test With Objects</title>
</head>
<li id="aaron-family">Hey, this is where it goes</li>
<footer>
<script src="objects.js"></script>
</footer>
</html>
解决方案
Well, you've got a couple problems there (<li>
tag without a parent <ol>
or <ul>
tag, among others)...but I'd say the primary error is that you are replacing each subsequent output with each assignment to innerHTML
.
Solution: assign a compiled array to innerHTML
(using join
to include spaces between the values)
var list = function(family) {
var names = [];
for (var prop in family) {
names.push(prop.name);
}
document.getElementById('aaron-family').innerHTML = names.join(' ');
}
list(family);
这篇关于显示JavaScript对象的列表作为HTML列表项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文