简体   繁体   English

如何使用 javascript 使用 DOM model 创建 Html 表?

[英]How to create a Html table using DOM model using javascript?

How to create a Html table using DOM model using Javascript?如何使用 Javascript 使用 DOM model 创建 Html 表?

for ex:例如:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tblMCNRoles">   
</table>

I have above table and i want to render above table like below by using DOM modal creation.我有上表,我想通过使用 DOM 模态创建来呈现上表,如下所示。

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tblMCNRoles">

<tr>
 <td bordercolor="green" align="center" valign="top" style="border-style:dotted" >
   <table width="99%" border="0" cellspacing="0" cellpadding="0" 
      class="portlet-table-body intable5"> 
      <tr><td align="center" valign="middle" class="grid6"></td></tr>
   </table>
 </td>
</tr>
</table>

I suggest you use the DOM Table methods since neither appendChild nor innerHTML are good for safe cross browser manipulation.我建议您使用 DOM Table 方法,因为 appendChild 和 innerHTML 都不适用于安全的跨浏览器操作。

The DOM has insertRow and insertCell which works better. DOM 有 insertRow 和 insertCell 效果更好。

Here is IE's documentation and here is an example from Mozillas Developer Network这是IE 的文档,这是来自Mozillas Developer Network的示例

<table id="table0">
 <tr>
  <td>Row 0 Cell 0</td>
  <td>Row 0 Cell 1</td>
 </tr>
</table>

<script type="text/javascript">

var table = document.getElementById('table0');
var row = table.insertRow(-1);
var cell, text;
for (var i=0; i<2; i++) {
  cell = row.insertCell(-1);
  text = 'Row ' + row.rowIndex + ' Cell ' + i;
  cell.appendChild(document.createTextNode(text));
}

</script>
var table = document.getElementById("tblMCNRoles");
var tr = document.createElement("tr");
var td = document.createElement("td");
//set attributes via setAttribute()
//add subtable via createElement and appendCHild
tr.appendChild(td);
table.appendChild(tr);

Or you can use innerHTML, but then you have to generate the HTML first或者你可以使用innerHTML,但是你必须先生成HTML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM