首页 > 解决方案 > 为什么 innerHTML 不能保留以前的状态(应该改用什么?)

问题描述

看起来innerHTML(以某种方式)与以下行为相同document.write():都删除了以前的 html。我使用的id是相同的元素(需要显示结果),但是使用innerHTML,我只得到列出的最后一个结果(最后一个对象),而不是把它们全部列出。我试过getElementsByClassName了,但没有显示任何东西。

function drawTd (item) {
  outputHTML += '<td>' + item + '</td>';
  document.getElementById('demo').innerHTML = outputHTML;
}

function drawSpecialTd (item) {
  outputHTML += item + '</br>';
  document.getElementById('demo').innerHTML = outputHTML;
}

  
for (var i=0; i<10; i++){
  // array1 and array2 have each iteration 1 single value
  // but array3 may have more
  var outputHTML = '';
  outputHTML = '<table>';
  outputHTML += '<tr>';
  array1.forEach(drawTd);
  array2.forEach(drawTd);
  outputHTML += '<td>';
  array3.forEach(drawSpecialTd);
  outputHTML += '</td>';
  outputHTML += '</tr>';
  outputHTML = '</table>';
}
<div id="demo" class="Classe"></div>

标签: javascripthtmldom

解决方案


请查看以下是否是您想要实现的(通过更改 innerHTML 对元素进行重复操作):

function repeat1()
{
var temp1=document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML=temp1+"-repeated";
}
<input type=button onclick="javascript:repeat1();" value="Please click">
<div id=demo></div>


推荐阅读