<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>對錶格操作</title>
<style type="text/css">
*{
padding:0px;
margn:0px;
}
table#stuRecordTable{width:600px;margin:40px auto;text-align: center;}
table#stuRecordTable tr{height:30px;}
</style>
<script type="text/javascript">
function $(eleStr){
switch(eleStr.substr(0,1)){
case "#":
return document.getElementById(eleStr.substr(1));
break;
case ".":
return document.getElementsByClassName(eleStr.substr(1));
break;
case "_":
return document.getElementsByName(eleStr.substr(1));
break;
default:
return document.getElementsByTagName(eleStr);
break;
}
}
onload = function(){
doOperator();
}
function doOperator(){
var updates =$(".update");
var dels =$(".del");
for (var i = 0; i < dels.length; i++) {
dels[i].onclick = function(){
if(confirm("是否確定刪除?")){ //提示是否刪除
//var row = this.parentNode.parentNode; //取到tr物件
//row.parentNode.removeChild(row); //移除tr
$("#stuRecordTable").deleteRow(this.parentNode.parentNode.rowIndex);
}
}
updates[i].onclick = function(){
var operatorCell = this.parentNode.parentNode.getElementsByTagName("td")[1]; //取到要操作的td物件
//1.修改按鈕上有兩個功能:修改,確定修改
if(this.value == "修改"){
this.value = "確定";
operatorCell.innerHTML ="<input value='"+operatorCell.innerHTML+"'/>";//把內容變成文字框
//做修改操作
}else{
operatorCell.innerHTML =operatorCell.getElementsByTagName("input")[0].value;//把文字框變成內容
this.value = "修改";
//做確定修改
}
}
}
}
function addRow(){
var rs = $("#stuRecordTable").rows; //table取到所有的行
var insertR = $("#stuRecordTable").insertRow(rs.length-1); //給表格新增一行(不包單元格)
//insertR.innerHTML = rs[1].innerHTML;
var c1 = insertR.insertCell(0);
c1.innerHTML = "yc" +Math.round(Math.random() * 101);
var c2 = insertR.insertCell(1);
c2.innerHTML = Math.round(Math.random() * 101);
var c3 = insertR.insertCell(2);
c3.innerHTML ='<input type="button" value="刪除" class="del"/><input type="button" value="修改" class="update"/>';
doOperator();
var cs = rs[1].cells; //取到當前行的所有單元格
//alert(cs[1].innerHTML);
}
</script>
</head>
<body>
<table id="stuRecordTable" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>姓名</th>
<th>成績</th>
<th>編輯</th>
</tr>
<tr>
<td>小明</td>
<td>90</td>
<td><input type="button" value="刪除" class="del"/>
<input type="button" value="修改" class="update"/></td>
</tr>
<tr>
<td>小紅</td>
<td>80</td>
<td><input type="button" value="刪除" class="del"/>
<input type="button" value="修改" class="update"/></td>
</tr>
<tr>
<td colspan="3">
<input type="button" value="新增" onclick="addRow()"/></td>
</tr>
</table>
</body>
</html>
複製程式碼