<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> <Html xmlns = "http://www.w3.org/1999/xhtml"> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Title> dynamically create a table (and delete rows and columns) </title> <Style type = "text/css"> Body, div { Margin: 0; Padding: 0; Font-size: 14px; } Table { Margin: 0 auto; } Td { Border: 1px solid green; Text-align: center; } </Style> <Script type = "text/javascript"> // Dynamically create a table Function createTable (){ Var divMain = document. getElementById ("divMain "); RemoveAllChild (divMain); // Delete the table that was last added Var myTable = document. createElement ("table "); MyTable. id = "DynamicTable "; Var myRow = document. getElementById ("myRow"). value; Var myCol = document. getElementById ("myCol"). value; Var trNode; Var tdNode; Var strTmp; For (var I = 1; I <= myRow; I ++ ){ TrNode = myTable. insertRow (-1 ); For (var j = 1; j <= myCol; j ++ ){ StrTmp = "row" + I + ", column" + j + "; TdNode = trNode. insertCell (-1 ); TdNode. innerHTML = "<a href = 'javascript: void (0); '>" + strTmp + "</a> "; } } DivMain. appendChild (myTable); // Add the table to the div // Event. srcElement. disabled = "true"; // disable the Add button. } // Delete All subnodes under a specified Node Function removeAllChild (nodeObj ){ While (nodeObj. hasChildNodes ()){ NodeObj. removeChild (nodeObj. firstChild ); } } // Delete a row Function DeleteRow (){ Var rowNum = document. getElementById ("delRow"). value; Var tbl = document. getElementById ("DynamicTable "); If (tbl = null ){ Alert ('create a table first '); Return; } If (rowNum <= tbl. rows. length) & (rowNum> 0 )){ Tbl. deleteRow (rowNum-1 ); } Else { Alert ('enter a valid row! '); } } // Delete a column Function DeleteCol (){ Var colNum = document. getElementById ("delCol"). value; Var tbl = document. getElementById ("DynamicTable "); If (tbl = null ){ Alert ('create a table first '); Return; } If (tbl. rows. length <= 0 ){ Alert ('table does not have row '); Return; } If (colNum <= tbl. rows [0]. cells. length) & (colNum> 0 )){ For (var I = 0; I <tbl. rows. length; I ++ ){ Tbl. rows [I]. deleteCell (colNum-1 ); } } Else { Alert ('specifies that the column does not exist '); } } </Script> </Head> <Body> Enter the number of rows <input type = "text" id = "myRow"/>. Enter the number of columns. <Input type = "text" id = "myCol"/> <br/> <Input type = "button" value = "create table" onclick = "createTable ()"/> <br/> <Input type = "text" id = "delRow"/> <input type = "button" value = "Delete row" Onclick = "DeleteRow ()"/> <br/> <Input type = "text" id = "delCol"/> <input type = "button" value = "delete column" Onclick = "DeleteCol ()"/> <br/> <Div id = "divMain"> </Div> </Body> </Html> |