如果想在网页里用JS动态增加表格的行,
有一种就是使用table.addRow(),然后再用row.addCell(),然后一个一个创建,创建完一行后,使用table.insertBefore或者appendChild来添加,,
但是这样有一点不好,如果这一行包括不少的列,而且又有CSS,又有事件等,,就麻烦了。。。
所以有一个办法是克隆的办法,就是有一行称为模板行的,将其隐藏起来(例如放在一个隐藏层里即可),然后在使用先用cloneNode(true)把行复制下来,再修改一些必要的属性,然后再用insertBefore等即可哈。。
我有一个是这样做的,因为每一行的几乎相同,只有ID和NAME以及背景色等稍有不同,,所以我这样做了一个
每一行里的ID号NAME包含着一个特殊的字符串_blank_,这个是等会要替换成行号的。。。
function replaceIdName(obj, nIndex) { // if (obj.id != undefined) { obj.id = replaceIndex(obj.id, nIndex); } if (obj.name != undefined) { obj.name = replaceIndex(obj.name, nIndex); } } //----------------------------------------------------------------------------- function replaceIndex(s, nIndex) { // if (s !=undefined) { s = s.replace(/_blank_/g, String(nIndex)); } return s; } //----------------------------------------------------------------------------- function replaceBackground(s, nIndex) { // if (nIndex % 2 == 0) { s = s.replace(/TextField1/g, "TextField2"); } return s; } //----------------------------------------------------------------------------- function addNewRow(oTable, oRow, oBefore, nIndex) { //add a new row according to the row, and insert into the oBefore TR in the table
//copy the row var oNewRow = oRow.cloneNode(true);
//apply the row replaceIdName(oNewRow, nIndex); var nRowColor = ((nIndex%2==0) ? color_even : color_odd); oNewRow.background = nRowColor;
//change cells in the row for (var i=0; i < oNewRow.childNodes.length; i++) { oCell = oNewRow.childNodes[i]; replaceIdName(oCell, nIndex); oCell.innerHTML = replaceIndex(oCell.innerHTML, nIndex); //set correct background oCell.innerHTML = replaceBackground(oCell.innerHTML); }
//alert(oNewRow.outerHTML); oTable.insertBefore(oNewRow, oBefore); } //-----------------------------------------------------------------------------
|