<!DOCTYPE html>
<html lang="en">
<!----
这里通过原生js实现了表格输入功能,
总体分为一下步骤
1,创建一个表格
2,event.srcElement 获取激活事件的对象,获取已经点击的单元格索引
3,通过处理函数abc()判断输入内容并将内容显示在新的表格中。
-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
table,
table td,
table tr {
border: 1px solid #000000;
width: 600px;
height: 50px;
text-align: center;
border-collapse: collapse;
overflow: hidden
}
input {
width: 30px;
height: 30px;
border:0;
}
</style>
<body>
<table id="tb_1" onclick="TabClick();">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>h</td>
<td>i</td>
<td>j</td>
<td>k</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
<script>
function TabClick(){
var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
// alert("行号:" + (td.parentElement.rowIndex) + ",列号:" + td.cellIndex);
let str =''
if(td.parentElement.rowIndex != undefined || td.cellIndex != undefined){
str = td.parentElement.rowIndex.toString() +td.cellIndex.toString()
var oldCellValue = td.innerHTML
//在单元格中插入一个input,并将它的id设置成行列组成的数字,将这个单元格的索引传递给失去焦点触发的函数,并将单元格的旧数据传递过去
//td.innerHTML="<input id='"+str+"' type='text' onblur = abc("+td.parentElement.rowIndex+","+td.cellIndex+","+oldValue+") name='temp' value='' >";
td.innerHTML="<input id='"+str+"' type='text' onblur = abc('"+td.parentElement.rowIndex+"','"+td.cellIndex+"','"+str.toString()+"','"+oldCellValue+"') name='temp' value='"+oldCellValue+"'/>";
var input1=document.getElementById(str); //获取到创建的input
input1.focus(); //让input获得焦点
} else {
console.log('否则'+td.parentElement.rowIndex);
}
}
function abc(row,cell,nInputId,oldCellValue){ //处理input失去焦点时的动作
/*
1,通过ID获得创建的input
2,通过ID获得当前表格
3,判断input是否输入了值
3.1没有输入就写入单元格之前的值
3.2输入了就写入输入过的值
4,通过传递过来的表格索引,给当前点击的单元格写入内容
*/
let nInput = document.getElementById(nInputId)
let table= document.getElementById('tb_1')
nInput.onchange = function(){
console.log('aaa')
}
if(nInput.vallue !='' ){
console.log(oldCellValue)
console.log(nInput.value)
table.rows[row].cells[cell].innerHTML = nInput.value
console.log('不是空的')
} else {
console.log('空')
table.rows[row].cells[cell].innerHTML = oldCellValue
}
if(table.rows[row].cells[cell] == ''){
table.rows[row].cells[cell].innerHTML = oldCellValue
}
}
</script>
</body>
</html>