一个可编辑的表格
通过双击进行编辑,回车确认编辑内容,如果不回车确认.那么恢复原来的值
效果图如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table{
border: 1px solid #333;
border-spacing:10px 20px;
border-collapse:separate;
font-size: 14px;
}
td,th{
height: 30px;
width: 100px;
border-radius: 5p;
border: 1px solid #333;
border-collapse:separate;
}
</style>
</head>
<body>
<table>
<caption>人员信息登记表</caption>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>部门</th>
<th>薪资</th>
<th>工龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>3年</td>
</tr>
<tr>
<td>李四</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>5年</td>
</tr>
<tr>
<td>张三</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>3年</td>
</tr>
<tr>
<td>张三</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>3年</td>
</tr>
<tr>
<td>张三</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>3年</td>
</tr>
<tr>
<td>张三</td>
<td>22</td>
<td>男</td>
<td>技术部</td>
<td>12K</td>
<td>3年</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6"></td>
</tr>
</tfoot>
</table>
<script>
window.onload=function ()
{
var mytd =document.getElementsByTagName('td');
var newTd =[];
// console.log(mytd);
for (let i=0;i<mytd.length;i++){
newTd[i]=mytd[i].innerHTML;
}
for (var i=0;i<mytd.length;i++)
{
mytd[i].ondblclick = function ()
{
var inputNum = document.getElementsByTagName('input')
// if (inputNum.length>0){
// return false;
// }
for(let i=0; i<this.childNodes.length; i++){
if(this.childNodes[i].nodeName=='INPUT'){
return false;
}
}
for (let j = 0; j<mytd.length;j++)
{
var inputN= mytd[j].getElementsByTagName('input')
if (inputN.length>0)
{
var inpt=newTd[j];
inputN.onkeyup=function ()
{
var event =e || window.event;
if (event.key == 'Enter')
{
inpt = inputN[0].value;
}else {
inpt=newTd[j].innerHTML;
}
}
mytd[j].removeChild(inputN[0]);
// console.log(inpt);
mytd[j].innerHTML =inpt;
// console.log(newTd[j]);
}
}
var tdText = this.innerHTML;
this.innerHTML = '';
// console.log(myinput.value);
var myinput = document.createElement('input');
myinput.setAttribute('type','text');
myinput.style.cssText="border:0px;font-size:14px;width:95%;outline:none;";
myinput.value =tdText;
this.appendChild(myinput);
myinput.focus();
myinput.select();
var tdo =this;
myinput.onkeyup =function (e)
{
// console.log(e.code);
var event =e || window.event;
if (event.key == 'Enter')
{
tdo.innerHTML =this.value;
tdText = this.value;
}
else if (event.key == 'Escape')
{
console.log(tdText);
tdo.innerHTML = tdText;
// inputText = tdText;
}
}
myinput.ondblclick=function(e)
{
return false;
}
}
}
}
</script>
</body>
</html>