微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 用于循环覆盖HTML中的文本

我的名为myEmployees的数组中有5个名字,但是当我运行代码时,它只打印出其中的3个.我相信这种情况正在发生,因为脚本中的for循环覆盖了它在HTML文档中编写的前一行.我怎样才能解决这个问题?

Yearly Bulletin Board Announcements!

Congratulations to Taylor, you have been here for 9 years and you meet the magic number! You get 2 extra weeks of PTO!

Derek, thank you for your service over the past 8 years. I look forward to many more years working with you!

Tyler, no longer works here.

以上是我运行代码时在屏幕上显示内容,应该有另外两个语句出现.任何建议将不胜感激!

<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.`)
    }
};

解决方法:

你是对的 – innerHTML覆盖了以前的值 – use =而不是:

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!`);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐