table指定位置添加行

<html> 
<head> 
<script type="text/javascript"> 
//global var 
var pos =0 
//to find the position you mouse has pressed 
function whichElement(e) 
{ 
var targ 
if (!e) var e = window.event 
if (e.target) targ = e.target 
else if (e.srcElement) targ = e.srcElement 
if (targ.nodeType == 3) // defeat Safari bug 
targ = targ.parentNode 
if(targ.tagName=="TD"){//to adjust whether the element is tabledata 
pos = targ.parentNode.rowIndex+1 
} 
else if(targ.tagName=="INPUT"){ 
//to do nothing 
} else{ 
pos =0 
} 
//alert(pos) 
} 
//to insert a row in the place 
function insRow() 
{ 
//alert(pos) 
var x=document.getElementById('myTable').insertRow(pos) 
var y=x.insertCell(0) 
var z=x.insertCell(1) 
y.innerHTML=document.getElementById("cell1").value 
z.innerHTML=document.getElementById("cell2").value 
} 
</script> 
</head> 
<body onmousedown="whichElement(event)"> 
<table id="myTable" border="1"> 
<tr> 
<td>Row1 cell1</td> 
<td>Row1 cell2</td> 
</tr> 
<tr> 
<td>Row2 cell1</td> 
<td>Row2 cell2</td> 
</tr> 
<tr> 
<td>Row3 cell1</td> 
<td>Row3 cell2</td> 
</tr> 
</table> 

 
<p> 
Cell1:<input type="text" id= "cell1" value="cell1"/> 
Cell2:<input type="text" id= "cell2" value="cell2"/> 
</p> 
<input type="button" onclick="insRow()" value="插入行"> 
</body> 
</html>

欢迎评论。。。。让我看到你的反馈。。。。

原文地址:https://www.cnblogs.com/rzm2wxm/p/5624095.html