表格的操作
对表格完成如下操作:
1、表格隔行变色
2、鼠标移动上去变色
3、增加行
4、删除行
5、修改行
HTML代码片
:
<table id="tab">
<tr>
<td>编号</td>
<td>姓名</td>
<td>操作</td>
</tr>
<tr>
<td>001</td>
<td>张三</td>
<td><a href="#" id="close" onclick="deleteRow(this)">删除</a></td>
</tr>
<tr>
<td>002</td>
<td>张三</td>
<td><a href="#" id="close" onclick="deleteRow(this)">删除</a></td>
</tr>
<tr>
<td>003</td>
<td>张三</td>
<td><a href="#" id="close" onclick="deleteRow(this)">删除</a></td>
</tr>
<tr>
<td>004</td>
<td>张三</td>
<td><a href="#" id="close" onclick="deleteRow(this)">删除</a></td>
</tr>
</table>
<hr>
<from>
<label>编号:</label><input type="text" /><br>
<label>姓名:</label><input type="text" /><br>
<button type="button">添加</button>
<button type="button">删除</button>
<button type="button">修改</button>
</from>
JS代码片
:
<script type="text/javascript">
var mytab=document.getElementById("tab");
var mytr=mytab.rows;
// 操作属性
mytab.border="1";
mytab.width="500";
mytab.cellPadding="0";
mytab.cellSpacing="0";
// 操作样式
// mytab.style.border="1px solid red";
// mytab.style.width="500px";
// mytab.style.height="500px"
for(var i=0;i<mytr.length;i++){
if(i%2==0){
mytr[i].style.backgroundColor="#ddd";
}
mytr[i].onmouseover=function(){
this.style.backgroundColor="red";
this.style.color="white";
}
mytr[i].onmouseout=function(){
if(i%2==0){
mytr[i].bgColor="#ddd";
this.style.backgroundColor="#ddd";
this.style.color="black";
}else{
this.style.backgroundColor="white";
this.style.color="black";
}
}
}
var mybtn=document.getElementsByTagName("button");
var myinput=document.getElementsByTagName("input");
// 删除操作
mybtn[1].onclick=function(){
var inputTxt=myinput[0].value;
for(var i=1;i<mytr.length;i++){
var tdTxt=mytr[i].cells[0].innerText;
if(inputTxt==tdTxt){
mytab.deleteRow(i);
}else{
alert("编号不存在,请重新输入!")
}
}
}
function deleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("tab").deleteRow(i);
}
// 修改操作
mybtn[2].onclick=function(){
var inputTxt=myinput[0].value;
for(var i=1;i<mytr.length;i++){
var mytd=document.getElementById('tab').rows[i].cells;
var tdTxt=mytr[i].cells[0].innerText;
if(inputTxt==tdTxt){
mytd[1].innerText=myinput[1].value;
}
}
}
// 添加操作
mybtn[0].onclick=function(){
// 编号是否重复
var inputTxt=myinput[0].value;
var con=true;
for(var i=1;i<mytr.length;i++){
var tdTxt=mytr[i].cells[0].innerText;
if(inputTxt==tdTxt){
con=false;
break;
}
}
if(con){
// 添加行开始
var newTr=mytab.insertRow(); //<tr></tr>
for(var i=0;i<3;i++){
var newTd=newTr.insertCell();
if(i==2){
newTd.innerHTML="<a href='#' id='close' οnclick='deleteRow(this)'>删除</a>"
}else{
newTd.innerText=myinput[i].value;
}
}
// 添加行结束
}else{
alert("编号重复,不能添加")
}
}
</script>
效果如下:
原效果:隔行变色
鼠标移动上去背景色变为红色:
单击操作删除,删除的是一行,还可以对表格进行添加,修改和删除操作