Home >Web Front-end >HTML Tutorial >Dynamically add, modify and delete html table content_html/css_WEB-ITnose
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Dynamic Table</title><script type="text/javascript" src="js/dynamic_table.js"> </script></head><body><table><tr><th>名称</th><th>颜色</th><th>尺寸</th><th>单价</th><th>折扣</th><th>数量</th><th>金额</th></tr><tbody id="goods"></tbody><tr><td><input type="button" value="add" onClick="addRow('多彩1234', '红色', 'XL', '1000.00', '1.00', '1', '1000.00')" /></td><td><input type="button" value="del" onClick="removeRow('goods', '0')"/></td><td><input type="button" value="modify" onClick="modifyRow('goods', '0', '0', '张小宝')" /></td><td><input type="button" value="clear" onClick="clearRows('goods')"/></td></tr></table></body></html>
onerror=handleErrvar txt=""function handleErr(msg,url,l) { txt="本页中存在错误。\n\n" txt+="错误:" + msg + "\n" txt+="URL: " + url + "\n" txt+="行:" + l + "\n\n" txt+="点击“确定”继续。\n\n" alert(txt) return true}function addRow(name, color, size, unit, discount, count, sum) { var bodyObj=document.getElementById("goods"); if(bodyObj==null) { alert("Body of Table not Exist!"); return; } var rowCount = bodyObj.rows.length; //var cellCount = myarray.length; var newRow = bodyObj.insertRow(rowCount++); newRow.insertCell(0).innerHTML=name; newRow.insertCell(1).innerHTML=color; newRow.insertCell(2).innerHTML=size; newRow.insertCell(3).innerHTML=unit; newRow.insertCell(4).innerHTML=discount; newRow.insertCell(5).innerHTML=count; newRow.insertCell(6).innerHTML=sum;}function removeRow(tbodyID, row) { var bodyObj=document.getElementById(tbodyID); if(bodyObj==null) { alert("Body of Table not Exist!"); return; } var nrow = Number(row); if (nrow <= bodyObj.rows.length) bodyObj.deleteRow(nrow); else alert("nrow is less.");}function modifyRow(tbodyID, row, col, newvalue) { var nrow = Number(row); var ncol = Number(col); var bodyObj=document.getElementById(tbodyID); if(bodyObj==null) { alert("Body of Table not Exist!"); return; } try { //var tableObj = bodyObj.parentNode; if (nrow < bodyObj.rows.length && ncol < bodyObj.getElementsByTagName('tr')[nrow].getElementsByTagName('td').length) { //这个在ie下可以 在google下不行 //bodyObj.rows(nrow).cells(ncol).innerHTML = newvalue; //bodyObj.rows[nrow].childNodes[ncol].innerHTML = newvalue; //这个在ie和google下都可以 document.getElementById(tbodyID).getElementsByTagName('tr')[nrow].getElementsByTagName('td')[ncol].innerHTML = newvalue; } else alert("empty."); } catch (err) { alert(err.description); }}function clearRows(tbodyID) { var bodyObj=document.getElementById(tbodyID); if(bodyObj==null) { alert("Body of Table not Exist!"); return; } for (var i = 0; i < bodyObj.rows.length; ) bodyObj.deleteRow(i);}
Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.