【问题标题】:For loop overwriting text in HTMLFor循环覆盖HTML中的文本
【发布时间】: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


【解决方案1】:

你是对的——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!`);

【讨论】:

  • 这解决了,谢谢!它让我现在朝着正确的方向前进。
  • @bemon -- 不客气!祝你好运,编码愉快!
【解决方案2】:

您确实在覆盖您之前插入的内容。我不会使用一系列标题标签,而是使用&lt;ol&gt; 标签来表示“win”、“here”和“notHere”,并在满足必要条件时从数组中追加元素。

【讨论】:

  • 我不知道为什么我没有想到这一点……下一个好主意让我牢记这一点。我以前做过,所以现在你提到它,我很惊讶我没有想到那条路线。
【解决方案3】:

下面的语句覆盖了现有的 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!`);

【讨论】:

    【解决方案4】:

    使用insertAdjacentHTML

    document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')
    

    它可以有better performance而不是使用innerHTML,尤其是在使用beforeend时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多