实现功能:
1.可以在表格里点击,然后直接修改内容。
2.在表格中,按esc撤销修改操作,按回车确认修改。
实现步骤:
1.给表格添加点击事件,如果点击在表格中添加一个<input>标签
2.将表格中原来的内容置为空,并把内容放在input标签里
3.将input标签聚焦并选中
4.给input添加监听
注意事项:
1.需要注意处理点击表格后,再次点击可能会把input标签内的内容输出。
代码:
1.editTable.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>可以编辑的表格</title>
<link type="text/css" rel = "stylesheet" href="css/editTable.css" />
<script src="js/jquery.js"></script>
<script src="js/editTable.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th colspan="2">可以编辑的表格</th>
</tr>
</thead>
<tbody>
<tr>
<th>学号</th>
<th>姓名</th>
</tr>
<tr>
<td>1</td>
<td>张三</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
</tr>
<tr>
<td>3</td>
<td>王五</td>
</tr>
<tr>
<td>4</td>
<td>呵呵</td>
</tr>
<tr>
<td>5</td>
<td>周六</td>
</tr>
<tr>
<td>6</td>
<td>王五</td>
</tr>
<tr>
<td>7</td>
<td>王五</td>
</tr>
</tbody>
</table>
</body>
</html>
2.editTable.css
table{
border:1px solid black;
/*修正单元格不能合并*/
border-collapse: collapse;
width: 200px;
margin-left: 200px;
}
table th{
border:1px solid black;
border-collapse: collapse;
}
table tr{
border:1px solid black;
border-collapse: collapse;
}
table td{
border:1px solid black;
border-collapse: collapse;
}
tbody th{
background-color:navajowhite;
}
3.editTable.js
$('document').ready(function(){
$('tbody tr:even').css('background-color','#abcdef');
$('tbody tr:odd').css('background-color','#fedcba');
var Td = $('tbody td');
Td.click(function(){
//保存原来的内容并将原来的内容清空
var tdObj = $(this);
//如果含有input标签 就不进行下面操作;
if($(tdObj).children('input').length>0){
return false;
}
var oddText = $(this).html();
$(this).html('');
//添加一个新的输入框 并填入数据
var input = $('<input type="text">').appendTo($(this))
.val(oddText)
.width($(this).width())
.css('border','0px')
.css('background-color',$(this).css('background-color'));
//将文本选中
input.trigger('target').trigger('select');
//阻止文本框的事件向上传递
input.click(function(){
return false;
});
//添加按键事件
input.keyup(function(event){
var keycode =event.which;
if(keycode == 13){
//将td里的内容改变
tdObj.html(input.val());
}
if(keycode == 27){
tdObj.html(oddText);
}
});
});
});