[英]Display all pupil data from object property of school class
I want to display all pupil data from 'pupils' which is an array of objects belonging to the School class. 我想显示来自“学生”的所有学生数据,“学生”是属于School类的一组对象。
I have created a new instance of the school class and a forEach loop which takes each pupil object and uses document.getElementById().innerHTML
to display each property of the object in paragraph text. 我创建了学校课程的新实例和一个forEach循环,该循环接收每个瞳孔对象,并使用
document.getElementById().innerHTML
在段落文本中显示该对象的每个属性。
class School {
constructor(name, level, pupils) {
this.name = name;
this.level = level;
this.pupils = pupils;
}
}
let pupils = [
{
name: 'John Doe',
age: 17,
grades: {
'English': 9,
'Maths': 9,
'Sociology': 'A*'
},
attendance: 45
},
{
name: 'Jane Doe',
age: 17,
grades: {
'English': 7,
'Maths': 6,
'Sociology': 'B'
},
attendance: 93
}
];
const myschool = new School('My School', 'high', pupils);
myschool.pupils.forEach(function(pupil) {
document.getElementById('pupils').innerHTML = `<h2>${pupil.name}
</h2><p>Age: ${pupil.age}</p><p>Attendance: ${pupil.attendance}
</p>`;
});
HTML: HTML:
<div id='pupils'>
</div>
My code correctly displays only one pupil (Jane Doe). 我的代码仅正确显示一个瞳孔(简·多伊)。 It should display both.
它应该同时显示。
<div id='pupils'>
<p>
Jane Doe
Age: 17
Attendance: 93
</p>
</div>
You're resetting the innerHTML
each time - innerHTML =
removes all previous content, so you'll only end up with the last pupil. 您每次都会重置
innerHTML
- innerHTML =
会删除所有先前的内容,因此您只会以最后一个瞳孔结束。 Use +=
to add the new HTML: 使用
+=
添加新的HTML:
document.getElementById('pupils').innerHTML += `<h2>${pupil.name}
</h2><p>Age: ${pupil.age}</p><p>Attendance: ${pupil.attendance}
</p>`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.