innerHTML元素位置错误 [英] innerHTML elements in wrong place

查看:97
本文介绍了innerHTML元素位置错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对innerHTML的理解并不完全清楚,所以我遇到了一些麻烦。

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

这会产生我在桌子外面的所有td。我做错了什么?

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

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


推荐答案

因为你附加了无效HTML,浏览器通过添加您错过的元素来帮助您。然后,当您添加表格单元格时,它们会在关闭的表格后附加。

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.

尝试添加表格,然后是行,然后是单元格。此外,首先构建整个字符串,然后一次性附加它,更新DOM(即使用 innerHTML )是一个缓慢的操作。

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;

这篇关于innerHTML元素位置错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆