JavaScript:table元素行的添加和删除

project cost days  
8792 63
 
 
 
 
source
代码
<html>

<head>

<title>js</title>
<script language="javascript" type="text/javascript">
var activeRow = 0;
function addRow()
{
var i;
var tb = document.getElementById("table1");
var row = tb.insertRow(activeRow + 1);

for(i=0;i<4;i++){
var cell = row.insertCell(i);
if(i == 0){
cell.innerHTML
= getInputString("text","");
cell.className
= "bd";
}
if(i == 1){
cell.innerHTML
= parseInt(Math.random()*1000);
cell.className
= "bd";
}
if(i == 2){
cell.innerHTML
= "30";
cell.className
= "bd";
}
if(i == 3){
cell.innerHTML
= getInputString("button"," L ");
}
}
}
function delRow()
{
var tb = document.getElementById("table1");
if (activeRow >= tb.rows.length){
activeRow
= tb.rows.length - 1;
}
tb.deleteRow(activeRow);
}

function getInputString(sType, sValue)
{
var str = "<input type='"+ sType +"' value='"+sValue+"' id='btn' ";
if(sType == "button"){
str
+= " onclick='getData();'";
}
str
= str + " />";
return str;
}
function getData()
{
currentRow();
var tb = document.getElementById("table1");
var v = parseInt(Math.random()*151+50);
tb.rows(activeRow).cells(
2).innerHTML = v;
}

function currentRow(){
var obj = event.srcElement;
if (obj.tagName == 'INPUT'){
obj
= obj.parentElement;
}
activeRow
= obj.parentElement.rowIndex;
}

</script>
<style type="text/css">
.bd
{ border:#ccc solid 1px;
margin
: 0px ;
padding
: 0px ;
font-size
: 20px ;
}

[type="button"]
{
border
:1px outset;
background-color
: #C0C0C0;
font-size
: 10pt;
}
[type="text"]
{
border
: inset 1px #eeeeee;
padding
:0px;
background-color
:Yellow;
vertical-align
:middle;
width
: 150px ;
height
: 30px ;
}
</style>
</head>

<body>
<div>
<table id="table1" onclick="currentRow();">
<tr>
<td width="100px">project</td>
<td width="50px">cost</td>
<td width="50px">days</td>
<td width="30px">&nbsp;</td>
</tr>
<tr>
<td class="bd"><input type="text" id="bRow2" value="kundianxian" /></td>
<td class="bd">8792</td>
<td class="bd">63</td>
<td><input type="button" value=" L " id="btn1" /> </td>
</tr>
</table>
</div>
<hr style=" 400px;" align="left"/>
<div>
<input type="button" value="row add" id="btnAdd" name="btnAdd" onclick="addRow();" />
<input type="button" value="row delete" id="btnDel" name="btnDel" onclick="delRow();" />
</div>

</body>

</html>
原文地址:https://www.cnblogs.com/cnbwang/p/1874840.html