javascript - For 循环覆盖 HTML 中的文本

标签 javascript html for-loop typescript

我的名为 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>

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 正在覆盖之前的值——使用 += 代替:

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

关于javascript - For 循环覆盖 HTML 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083750/

相关文章:

javascript - 确保垂直内容水平溢出

c++ - 'for' 循环内的后增量和预增量产生相同的输出

javascript - DataTables - 最后一列固定宽度

javascript - 用户在 noConflict mod 中使用 jQuery 定义函数

jquery - 使用 Bootstrap ,容器标题栏宽度不会达到 100%

java - 您好,尝试根据数组值打印一定数量的字符。 java

python - Tensorflow 在 python for 循环中太慢

javascript - 如何在 JavaScript 中描述函数参数的位置

javascript - 如何扩展 Xul 按钮并使其可聚焦?

c# - Openwebkitsharp - COMException 未处理?