js实现即时编辑网页内容方法二--表格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table border="1" width="500" align="center" class="tab">
<tr>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
</tr>
<tr>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
</tr>
<tr>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
</tr>
<tr>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
<td>DATA</td>
</tr>
</table>
</body>
<script>
var atd = document.querySelectorAll(".tab td");
for(var i=0;i<atd.length;i++){
atd[i].onclick = function(){
// 点击td时创建输入框
var ipt = document.createElement("input");
// 将输入框的内容设置为td的内容
ipt.value = this.innerHTML;
// 将td清空
this.innerHTML = "";
// 吧ipt插入进去
this.appendChild(ipt);
// 自动获取焦点
ipt.focus();
// 为了防止ipt被点击时,事件的冒泡重复执行td的点击,所以取消冒泡
ipt.onclick = function(eve){
var e = eve || window.event;
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble = true;
}
}
// 提前保存,外面的this
var that = this;
ipt.onblur = function(){
// 当ipt失去焦点时,将输入框的内容设置给td,同时删除输入框
that.innerHTML = this.value;
}
}
}
</script>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634817.html