If you want to dynamically add table rows in JavaScript on a webpage,
One way is to use table. addrow (), then use row. addcell (), and create one by one. After creating a row, use table. insertbefore or appendchild to add it ,,
But this is a little bad. If this row contains many columns, CSS, and events, it will be troublesome...
Therefore, there is a method of cloning, that is, a row called a template row is hidden (for example, in a hidden layer), and then clonenode (true) is used first) copy the row, modify some necessary attributes, and then use insertbefore ..
I did this because each row has almost the same ID, name, and background color, so I made
The ID number name in each row contains a special string _ blank _, which is to be replaced with a line number...
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 );
}
//-----------------------------------------------------------------------------