The example in this article describes how to implement a directly editable table with JQuery. Share it with everyone for your reference. The specific analysis is as follows:
Function:
Create a table where the user can directly modify the cell text after clicking on a cell.
In the editing state, the user can press the Enter key to confirm the modification and press the ESC key to cancel the modification.
The effect is as follows:
Things:
When the user clicks on a cell, a text box is immediately inserted into the cell, and its width and height are set to the same values as the cell. After the user confirms the input, clear all HTML code in the cell, and then set the content to the text the user just entered.
HTML code:
<table align="center"> <tr> <td>学号</td> <td>姓名</td> </tr> <tr> <td>001</td> <td>dog</td> </tr> <tr> <td>002</td> <td>cat</td> </tr> <tr> <td>003</td> <td>pig</td> </tr> </table>
JavaScript code:
$(function(){ $("td").click(function(event){ //td中已经有了input,则不需要响应点击事件 if($(this).children("input").length > 0) return false; var tdObj = $(this); var preText = tdObj.html(); //得到当前文本内容 var inputObj = $("<input type='text' />"); //创建一个文本框元素 tdObj.html(""); //清空td中的所有元素 inputObj .width(tdObj.width()) //设置文本框宽度与td相同 .height(tdObj.height()) .css({border:"0px",fontSize:"17px",font:"宋体"}) .val(preText) .appendTo(tdObj) //把创建的文本框插入到tdObj子节点的最后 .trigger("focus") //用trigger方法触发事件 .trigger("select"); inputObj.keyup(function(event){ if(13 == event.which) //用户按下回车 { var text = $(this).val(); tdObj.html(text); } else if(27 == event.which) //ESC键 { tdObj.html(preText); } }); //已进入编辑状态后,不再处理click事件 inputObj.click(function(){ return false; }); }); });
I hope this article will be helpful to everyone’s jQuery programming.