For循环覆盖HTML中的文本 [英] For loop overwriting text in HTML

查看:94
本文介绍了For循环覆盖HTML中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的名为myEmployees的数组中有5个名称,但是当我运行代码时,它只打印出其中3个.我相信这是因为脚本中的for循环正在覆盖它在HTML文档中编写的上一行.我该如何解决?

My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?

公告栏年度公告!

Yearly Bulletin Board Announcements!

恭喜您,泰勒,您已经在这里9年了,遇到了魔术号码!您将再获得2个星期的PTO!

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

Derek,感谢您过去8年的服务.我期待着与您合作的更多年!

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.

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

The above is what shows on my screen when I run the code, there should be two other statements to appear. Any suggestions would be greatly appreciated!

<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>

TypeScript

TypeScript

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正在覆盖先前的值-请改用+=:

You are correct-- innerHTML is overwriting the previous value-- use += instead:

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

这篇关于For循环覆盖HTML中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆