日期:2014-05-16 浏览次数:20454 次
function f(header){ var t = document.createElement("table"); t.innerHTML = header; for(var i=0; i<3; i++){ var tr = t.insertRow(table.rows.length); for(var j=0; j<2; j++){ var td = tr.insertCell(j); td.innerText = "aa_" + i + ", " + j; } } } f("<tr><th>col1</th><th>col2</th></tr>");
<div id="test"></div> <script type="text/javascript"> function f(header) { var oTest = document.getElementById("test"); var t = document.createElement("table"); t.innerHTML = header; for (var i = 0; i < 3; i++) { var tr = t.insertRow(t.rows.length); for (var j = 0; j < 2; j++) { var td = tr.insertCell(j); td.innerText = "aa_" + i + ", " + j; } } oTest.insertBefore(t, oTest.childNodes[0]); } f("<tr><th>col1</th><th>col2</th></tr>"); </script>
------解决方案--------------------
IE直接设置table的innerHTML会发生未知运行时错误,改为DOM操作就好了
function f(header) { header = header.split(','); var t = document.createElement("table"), tr, td, columnNum = header.length; document.body.appendChild(t); tr = t.insertRow(0); for (var i = 0; i < columnNum; i++) { td = document.createElement('th');tr.appendChild(td) ;td.innerHTML = header[i]; } for (var i = 0; i < 3; i++) { tr = t.insertRow(t.rows.length); for (var j = 0; j < columnNum; j++) { td = tr.insertCell(j); td.innerHTML = "aa_" + i + ", " + j; } } } window.onload = function () { f("col1,col2,col3,col4"); }
------解决方案--------------------
<table width="400px" border="1" style="border-collapse:collapse"> <thead id="tHead"></thead> <tr> <td>Smith</td><td>2000-01-23</td><td>Male</td><td>China</td> </tr> <tr> <td>Smith</td><td>2000-01-23</td><td>Male</td><td>China</td> </tr> </table> <script> var heads = [ [{ rowSpan: 2, align: 'center', innerHTML: 'Name' }, { colSpan: 3, align: 'center', innerHTML: 'Others'}]//第一行的td放数组里面 , [{ innerHTML: 'Birth' }, { innerHTML: 'Gender' }, { innerHTML: 'Address'}]//第一行的td放数组里面 ] , thead = document.getElementById('tHead'), tr, td, item, i, j, headLen = heads.length, tdLen; for (i = 0; i < headLen; i++) { tr = thead.insertRow(i); item = heads[i]; tdLen = item.length; for (j = 0; j < tdLen; j++) { td = tr.insertCell(j); for (attr in item[j]) td[attr] = item[j][att