方法一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table { text-align: center; } </style> <script> function delRow(id) { //取得要删除的那一行 var row = document.getElementById(id); var table = document.getElementById('mytb'); table.deleteRow(row.rowIndex); } function addrow() { var mytb = document.getElementById('mytb'); var index = mytb.rows.length - 1;//取得插入目标索引 var row = mytb.insertRow(index);//创建一个行 var id = 'row' + row.rowIndex;//拼接id row.setAttribute('id', id);//设置id var td0 = row.insertCell(0);//td0创建一个单元格 td0.innerHTML = "好看耐用超耐磨沙发两件套"; var td1 = row.insertCell(1); td1.innerHTML = row.rowIndex; var td2 = row.insertCell(2);//创建一个input按钮 td2.innerHTML = '<input type="button" value="删除订单" οnclick="delRow(\'' + id + '\')">'; } </script> </head> <body> <table border="1" cellspacing="0" cellpadding="0" id="mytb"> <tr> <td>商品名</td> <td>数量</td> <td>操作</td> </tr> <tr id="del1"> <td>好看耐用超耐磨沙发两件套</td> <td>24</td> <td><input type="button" value="删除订单" onclick="delRow('del1')"></td> </tr> <tr> <td colspan="3"><input type="button" value="增加订单" onclick="addrow()"></td> </tr> </table> </body> </html>
方法二:不同的地方就是input按钮的创建方法比较新颖
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> body { font: 13px/25px 宋体; } table { width: 360px; border-top: 1px solid #333; border-left: 1px solid #333; } tr { height: 30px; } table tr td { border-right: 1px solid #333; border-bottom: 1px solid #333; text-align: center; } </style> <script type="text/javascript"> function delRow(id) { //取得要删除的那一行 var row = document.getElementById(id); var table = document.getElementById('mytable'); table.deleteRow(row.rowIndex); } function addRow() { var table = document.getElementById('mytable'); //要插入的位置 var index = table.rows.length - 1; var row = table.insertRow(index);//只要知道行,可以知道其索引 var td0 = row.insertCell(0); td0.innerHTML = '抗疲劳神奇钛项圈'; var td1 = row.insertCell(1); td1.innerHTML = row.rowIndex; var td2 = row.insertCell(2); td2.innerHTML = '¥49.00'; var td3 = row.insertCell(3); var input = document.createElement('input'); input.setAttribute('type', 'button'); input.setAttribute('value', '删除'); input.onclick = function () { table.deleteRow(row.rowIndex); } td3.appendChild(input); } </script> </head> <body> <table border="0" cellspacing="0" cellpadding="0" id="mytable"> <tr> <td>商品名称</td> <td>数量</td> <td>价格</td> <td>操作</td> </tr> <tr id="del1"> <td>防滑真皮休闲鞋</td> <td>12</td> <td>¥568.50</td> <td><input type="button" value="删除" onclick="delRow('del1')"></td> </tr> <tr> <td colspan="4"><input type="button" value="增加订单" onclick="addRow()"></td> </tr> </table> </body> </html>