Dynamically add table rows
Text/Ray
The code in the table is as follows:
<Table id = "testtbl" border = 1>
<Tr id = "tr1">
<TD width = 6%> <input type = checkbox id = "box1"> </TD>
<TD id = "B"> first line </TD>
</Tr>
<Tr id = "tr2">
<TD width = 6%> <input type = checkbox id = "box2"> </TD>
<TD id = "B"> Row 2 </TD>
</Tr>
<Tr bgcolor = # 0000ff>
<TD width = 6%> <input type = checkbox id = "box3"> </TD>
<TD> Row 3 </TD>
</Tr>
</Table>
The JavaScript function for dynamically adding table rows is as follows:
Function addrow (){
// Add a row
VaR newtr = testtbl. insertrow ();
// Add two columns
VaR newtd0 = newtr. insertcell ();
VaR newtd1 = newtr. insertcell ();
// Set the column content and attributes
Newtd0.innerhtml = '<input type = checkbox id = "box4"> ';
Newtd2.innertext = 'new line ';
}
This is simple. Here is a detailed description:
1. inserrow () and insertcell () Functions
The insertrow () function can contain parameters in the following format:
Insertrow (INDEX)
This function adds a new row to the row of the index, such as insertrow (0), before the new row is added to the first row. The default insertrow () function is equivalent to insertrow (-1) and adds a new row to the end of the table.
Insertcell () and insertrow have the same usage.
2. dynamically set attributes and events
Innerhtml and innertext in the preceding rows are column attributes.
This inner is between "inner" and <TB> </TB>. innertext is the text added to <TB> </TB>, innerhtml is the HTML code added between <TB> </TB> (this so is simple, and this explanation is quite redundant)
You can set other attributes in the same way. For example, you can set the row background color.
Newtr. bgcolor = 'red ';
The same is true for setting events.
For example, I want to execute a self-defined function newclick when I click the new row. The number of newclick rows is as follows:
Function newclick (){
Alert ("this is the newly added line ");
}
The code for setting this function for the onclick event is as follows:
Newtr. onclick = newclick;
Here, the argument is: = the following part must be the function name and cannot contain quotation marks,
Newtr. onclick = newclick ();
Newtr. onclick = 'newclick ';
Newtr. onclick = "newclick ";
The above statements are all incorrect.
If you don't want to know why, you can skip the following section.
In fact, the newclick behind this = is a pointer to the self-defined newclick function. The function name in Javascript is a pointer to the function, and the browser that adds brackets cannot find the function.
The following statement is correct.
Newtr. onclick = function newclick (){
Alert ("this is the newly added line ");
}
This function name is actually the same
The usage of other events is the same.