【发布时间】:2017-03-29 03:25:52
【问题描述】:
我的名为myEmployees 的数组中有 5 个名称,但是当我运行代码时,它只打印出其中的 3 个。我相信这是因为脚本中的 for 循环覆盖了它在 HTML 文档中写入的前一行。我该如何解决这个问题?
年度公告板公告!
恭喜泰勒,你已经在这里工作了 9 年,你遇到了神奇的数字!您可以获得额外 2 周的 PTO!
Derek,感谢您在过去 8 年中的服务。我期待与您合作更多年!
泰勒,不再在这里工作。
以上是我运行代码时屏幕上显示的内容,应该还会出现另外两个语句。任何建议将不胜感激!
<body>
<h1>Yearly Buttetin Board Announcements!</h1>
<h2 id='win'></h2>
<h3 id='here'></h3>
<h4 id='notHere'></h4>
<script src='app.js'></script>
</body>
打字稿
for( i = 0; i < myEmployees.length; i++ ) {
const employee = myEmployees[i];
let magicNumber = employee.extraVacay;
let stillEmployed = employee.stillEmployed;
let timeInJob = employee.timeInJob;
let name = employee.name;
if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {
document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);
}
else if (stillEmployed == true) {
document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);
}
else {
document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
}
};
【问题讨论】:
-
仅在设置文本时使用
textContent而不是innerHTML,因为它更快(没有 HTML 解析和隐藏的 DOM 操作)但也很安全,因为它可以防止 HTML 注入(XSS 等)。跨度> -
您正在使用“.innerHTML =",这将覆盖您设置的最后一件事,因此上述代码永远不会超过 3 行。
标签: javascript html for-loop typescript