我也在几年前遇到过这个问题.
问题是,当您使用innerHTML属性添加HTML时,每次更新后,底层引擎将为您关闭未关闭的标记(并修复其他错误的HTML).所以在第二行之后,< table>和< tr>标签会自动关闭,之后的所有内容都只会写在表格之外.
方法1
(简单的方法)
使用字符串存储整个表的HTML并一次更新所有表.
var HTML = "
for(j=1;j<=10;j++)
{
HTML += "
"+String.fromCharCode(j+64)+"";}
HTML += "
";document.getElementById("outputDiv").innerHTML = HTML;
方法2
(更好的方式)
使用DOM函数
var table = document.createElement('table');
table.setAttribute('border','1');
table.setAttribute('width','100%')
var row = table.insertRow(0);
for(j=1; j<=10; j++){
var text = document.createTextNode(String.fromCharCode(j+64));
var cell = row.insertCell(j-1);
cell.setAttribute('align','center')
cell.appendChild(text);
}
document.getElementById("outputDiv").appendChild(table);
方法2增强
(更好的方法)
使用CSS而不是HTML属性.后者通常按最新规格折旧.
方法3
(很长一段路,但从长远来看是最好的)
$('
for(j=1; j<=10; j++)
$('
').text(String.fromCharCode(j+64)).appendTo('tr');