我的名为myEmployees
的数组中有5个名字,但是当我运行代码时,它只打印出其中的3个。我相信这种情况正在发生,因为脚本中的for
循环会覆盖它在HTML文档中编写的前一行。我该如何解决这个问题?
年度公告栏公告!
恭喜泰勒,你已经在这里待了9年,你遇到了神奇的数字!你得到额外2周的PTO!
德里克,感谢您在过去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.`)
}
};
答案 0 :(得分:4)
你是对的 - innerHTML
覆盖了以前的值 - 改为使用+=
:
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!`);
答案 1 :(得分:2)
您确实覆盖了之前插入的内容。我没有使用一系列标头标记,而是使用<ol>
标记来获胜,&#39; &#39;在这里,&#39;并且&#39; notHere&#39;,并在满足必要条件时附加数组中的元素。
答案 2 :(得分:1)
以下语句覆盖了现有的HTML。
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!`);
您必须将之前的值附加到新文本中。更新的代码应如下所示
var prevText = document.getElementById('here').innerHTML;
document.getElementById('here').innerHTML = prevText + (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);
答案 3 :(得分:0)
document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')
它可以比使用innerHTML better performance,尤其是在使用beforeend
时。