本文實例講述了jQuery實現的可編輯表格。分享給大家供大家參考,具體如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>可編輯表格</title> <script type = "text/javascript" src="jquery-1.7.2.min.js"></script> <style type = "text/css"> body{ background:#c0c0c0; } #tab{ border-collapse:collapse; } #tab td{ width:50px; height:18px; border:1px solid; text-align:center; } </style> <script type = "text/javascript"> $(function(){ var tds = $("#tab tr td"); editeTable(tds); }); function editeTable(tds){ tds.click(function(){ var td=$(this); var oldText=td.text(); var input=$("<input type='text' value='"+oldText+"'/>"); td.html(input); input.click(function(){ return false; }); input.css("border-width","1px"); input.css("font-size","12px"); input.css("text-align","center"); input.css("width","0px"); input.width(td.width()); input.trigger("focus").trigger("select"); input.blur(function(){ td.html(oldText); }); input.keyup(function(event){ var keyEvent=event || window.event; var key=keyEvent.keyCode; var input_blur=$(this); switch(key) { case 13: var newText=input_blur.val(); td.html(newText); changeCurrConAttrByTable(currTableId); break; case 27://按下esc鍵,取消修改,把文本框變成文本 td.html(oldText); break; } }); }); }; </script> </head> <body> <table id = "tab"> <tr> <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td> </tr> <tr> <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td> </tr> <tr> <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td> </tr> <tr> <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td> </tr> <tr> <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td> </tr> </table> </body> </html>