HTML : draw table using innerHTML

前端 未结 2 1086
长情又很酷
长情又很酷 2020-11-27 08:15
document.getElementById(\"outputDiv\").innerHTML = \"\";
document.getElementById(\"outputDiv\").innerHTML += \"\";
for(j=1         
2条回答
  •  粉色の甜心
    2020-11-27 08:56

    I ran into this problem years ago, too.

    The problem is that when you use the innerHTML property to add HTML, after each update, the underlying engine will close unclosed tag (and fix other bad HTML) for you. So after the second line, the

and tags are automatically closed and all content after that will just be written outside the table.


Method 1 (The easy way)

Use a string to store the HTML for the whole table and update it all at once.

var HTML = "
"; for(j=1;j<=10;j++) { HTML += ""; } HTML += "
"+String.fromCharCode(j+64)+"
"; document.getElementById("outputDiv").innerHTML = HTML;

​ Fiddle


Method 2 (The better way)

Use DOM functions

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

Fiddle


Method 2 enhanced (The yet better way)

Use CSS instead of HTML attributes. The latter is generally depreciated as of latest specs.

A great resource to start learning CSS is the Mozilla Developer Network

Fiddle


Method 3 (The long way, but the best in the long-run)

Use jQuery.

$('').append('').appendTo('#outputDiv');
for(j=1; j<=10; j++)
    $('
').text(String.fromCharCode(j+64)).appendTo('tr');

Fiddle

提交回复
热议问题