Js獲取table中當前選擇行號
<head>
<title>1</title>
<script>
//得到行物件
function getRowObj(obj)
{ var i = 0;
while(obj.tagName.toLowerCase() != "tr")
{ obj = obj.parentNode;
if(obj.tagName.toLowerCase() == "table")
return null;
}
return obj;
}
//根據得到的行物件得到所在的行數
function getRowNo(obj)
{ var trObj = getRowObj(obj);
var trArr = trObj.parentNode.children;
for(var trNo= 0; trNo < trArr.length; trNo++)
{ if(trObj == trObj.parentNode.children[trNo])
{ alert(trNo+1); }
}
}
//刪除行
function delRow(obj)
{ var tr = this.getRowObj(obj);
if(tr != null)
{
tr.parentNode.removeChild(tr);
}
else{
throw new Error("the given object is not contained by the table");
}
}
</script>
</head>
<body>
<table border = "1">
<tr>
<td>A<a href="#" onclick="getRowNo(this)">getRowNo<td>
</tr>
<tr>
<td>B<a href="#" onclick="delRow(this)">delRow<td>
</tr>
<tr>
<td>C<a href="#" onclick="getRowNo(this)">getRowNo</td>
</tr>
<tr>
<td>D<a href="#" onclick="getRowNo(this)">getRowNo</td>
</tr>
</table>
</body>
<html>