HTML : draw table using innerHTML

前端 未结 2 1048
长情又很酷
长情又很酷 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 <table> and <tr> 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 = "<table border=1 width=100%><tr>";
    for(j=1;j<=10;j++)
    {
        HTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
    }
    HTML += "</tr></table>";
    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.

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

    Fiddle

    0 讨论(0)
  • 2020-11-27 08:59

    I think the main problem is that your attributes are not quoted.

    But it's almost always a bad idea to repeatedly update the content of a dom element in a loop—each time you update dom content it causes some internal work to be done by the browser to make sure the page layout is current.

    I would build the html string up locally, then make one final update when done. (and of course make sure your attributes are quoted)

    document.getElementById("outputDiv").innerHTML = "";
    
    var newTable = "<table border='1' width='100%'><tr>";
    for(j = 1; j <= 10; j++) { //opening braces should always be on the same line in JS
        newTable += "<td align='center'>" + String.fromCharCode(j+64) + "</td>";
    }
    newTable += "</tr></table>";
    
    document.getElementById("outputDiv").innerHTML = newTable;
    
    0 讨论(0)
提交回复
热议问题