实现表格的增加,删除,复制,克隆
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>操作表格</title> <script> function append() { var thirdtr=document.getElementById('thirdtr'); var parents=thirdtr.parentNode; //创建一个tr var newtr=document.createElement('tr'); var newtd1=document.createElement('td'); newtd1.innerHTML="当幸福来敲门"; var newtd2=document.createElement('td'); newtd2.innerHTML=30; newtr.appendChild(newtd1); newtr.appendChild(newtd2); parents.insertBefore(newtr,thirdtr); } function dlnode(){ var sencondtr=document.getElementById('sencondtr'); var parents=sencondtr.parentNode; parents.removeChild(sencondtr); } function changesty() { var firsttr=document.getElementById('firsttr'); var firststy=firsttr.setAttribute('style','font:16px;background:#ccc'); } function clonnode() { var thirdtr=document.getElementById('thirdtr'); var parents=thirdtr.parentNode; // var newtr=document.createElement('tr') // var newtd1=document.createElement('td') // newtd1.innerHTML="幸福来敲门"; // var newtd2=document.createElement('td'); // newtd2.innerHTML="20"; var cl=thirdtr.cloneNode(true); parents.appendChild(cl); } </script> </head> <body> <table border="1" cellpadding="0" cellspacing="0"> <tr id="firsttr"> <td>书名</td> <td>价格</td> </tr> <tr id="sencondtr"> <td>看得见的风景</td> <td>20</td> </tr> <tr id="thirdtr"> <td>幸福来敲门</td> <td>30</td> </tr> </table> <input type="button" value="增加一行" id="appennode" onclick="append()"> <input type="button" value="删除第二行" id="dlnode" onclick="dlnode()"> <input type="button" value="修改标题样式" id="changesty" onclick="changesty()"> <input type="button" value="复制最后一行" id="copynode" onclick="clonnode()"> </body> </html>
2.利用表格特有方法实现增删和修改样式
<!DOCTYPE html> <html lang="en"> <style> .mytd { font: 12px/14px bold; color: red; } </style> <head> <meta charset="UTF-8"> <title>table row</title> <script> function append() { var mytb = document.getElementById('mytb'); var row=mytb.insertRow(2);//在目标位置插入一行 var td0=row.insertCell(0);//创建一个单元格 td0.innerHTML="幸福来敲门" var td1=row.insertCell(1); td1.innerHTML="20"; } function dele(){ var mytb = document.getElementById('mytb'); mytb.deleteRow(1); } function changesty() { var mytb = document.getElementById('mytb'); mytb.rows[0].className="mytd"; } </script> </head> <body> <table border="1" cellpadding="0" cellspacing="0" id="mytb"> <tr id="firsttr"> <td>书名</td> <td>价格</td> </tr> <tr id="sencondtr"> <td>看得见的风景</td> <td>20</td> </tr> <tr id="thirdtr"> <td>幸福来敲门</td> <td>30</td> </tr> </table> <input type="button" value="增加一行" onclick="append()"> <input type="button" value="删除第二行" onclick="dele()"> <input type="button" value="改变第一行样式" onclick="changesty()"> </body> </html>