javascript - 为什么 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>
解决方案
请查看以下是否是您想要实现的(通过更改 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>
推荐阅读
- firebase - 为什么将 redux 与 firebase 一起使用?
- c# - 根据c#中的条件将HTML字符串格式化为红色
- java - 字符串长度正确但仍然出错
- java - Kotlin 是否打破了封装规则?
- spring - Spring如何知道要引用哪个属性文件来获取带有@Value注释的变量的值?
- android - 在应用启动时获取信号强度级别
- python - 尝试使用 pip 时出现许多错误
- mysql - 如何在mysql LOAD DATA期间保留旧值?
- javascript - Amazon Mechanical Turk“自定义”通过网络界面提交
- php - 使用 php 和 LDAP 创建登录系统