innerHTML elements in wrong place

前端 未结 2 466
不知归路
不知归路 2020-12-22 05:27

My understanding of innerHTML isn\'t completely clear so I\'m having some trouble.

This produces all of my td\'s outside of the table. What am I doing wrong?

相关标签:
2条回答
  • 2020-12-22 06:10

    Since you're appending invalid HTML, the browser is helping you by adding the elements you missed out. Then, when you add your table cells, they get appended after the closed table.

    Try adding the table, then the row, then the cells. Also, build the whole string first then append it in one go, updating the DOM (ie. using innerHTML) is a slow operation.

    var list = document.getElementById("procTable");
    var listInner = "<table style='border:gray solid 1px;'><tr>";
    for (var i = 0; i < result.d.ProcessDataColumnModel.length; i++) {
       listInner += "<td style='border:gray solid 1px' width='" + (result.d.ProcessDataColumnModel[i].Width) + "'>" + (result.d.ProcessDataColumnModel[i].Caption) + "</td>";
    }
    listInner += "</tr></table>";
    list.innerHTML = listInner;
    
    0 讨论(0)
  • 2020-12-22 06:11

    This sometimes happen if you don't close your tags correctly. in your example:

    var list = document.getElementById("procTable");
    list.innerHTML = "<table style='border:gray solid 1px;'><tr>";
    for (var i = 0; i < result.d.ProcessDataColumnModel.length; i++) {
        list.innerHTML += "<td style='border:gray solid 1px' width='" + (result.d.ProcessDataColumnModel[i].Width) + "'>" + (result.d.ProcessDataColumnModel[i].Caption)+ "</td>";
    }
    list.innerHTML += "</tr></table>";
    
    0 讨论(0)
提交回复
热议问题