- <html>
- <head>
- <title>表格的单元格编辑</title>
- <style type="text/css">
- </style>
- </head>
- <body>
- <table border="1" align="center" id="table" width="600">
- <tr>
- <th>姓名</th>
- <th>年龄</th>
- <th>性别</th>
- <th>联系方式</th>
- </tr>
- <tr>
- <td>小赵</td>
- <td>25</td>
- <td>女</td>
- <td>15339125250</td>
- </tr>
- <tr>
- <td>小钱</td>
- <td>50</td>
- <td>男</td>
- <td>15339125251</td>
- </tr>
- <tr>
- <td>小孙</td>
- <td>20</td>
- <td>女</td>
- <td>15339125252</td>
- </tr>
- <tr>
- <td>小李</td>
- <td>19</td>
- <td>男</td>
- <td>15339125253</td>
- </tr>
- <tr>
- <td>小杨</td>
- <td>25</td>
- <td>女</td>
- <td>15339125254</td>
- </tr>
- <tr>
- <td>小宋</td>
- <td>12</td>
- <td>女</td>
- <td>15339125256</td>
- </tr>
- </table>
- <script type="text/javascript">
- //得到表格对象
- var tb = document.getElementById("table");
- //遍历每一个单元格,添加事件
- for (var i = 1; i < tb.rows.length; i++) {
- var tr = tb.rows[i];
- for (var j = 0; j < tr.cells.length; j++) {
- var td = tr.cells[j];
- td.onclick = beginEdit;
- }
- }
- function beginEdit(e){
- //得到事件参数对象
- ee = e || window.event;
- //由参数对象得到事件源对象(其实就是单元格对象)
- var target = e.target || e.srcElement;
- //该层If语句用于取消冒泡
- if (target.tagName == "TD") {
- var inputs = target.getElementsByTagName("input");
- if (inputs == false || inputs.length == 0){
- //把单元格原来的值保存
- var text = target.innerHTML;
- //把单元格原来的值清空
- target.innerHTML = "";
- //创建一个input元素
- var input = document.createElement("input");
- //添加input到target的子元素
- target.appendChild(input);
- //设置input元素的类型
- input.type = "text";
- input.size = "5";
- input.focus();
- //先把单元格原来的值添加到input元素中
- input.value = text;
- //input元素失去焦点
- input.onblur = function(e){
- ee = e || window.event;
- //事件源是input
- var target = e.target || e.srcElement;
- var td = target.parentNode;
- //innerHTML已经把input替换掉了,不需要再次一移除input
- td.innerHTML = target.value;
- }
- }
- }
- }
- </script>
- </body>
- </html>
该段代码实现了对单元格的编辑