<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function getValue(obj){
var tdElement=obj.parentNode;
var trElement=tdElement.parentNode;
var tableElement=trElement.parentNode;
alert(trElement.lastChild.id);
}
</script >
</head>
<body>
<table>
<tr id="aa">
<td>你好</td>
<td>哈哈</td>
<td>傻的</td>
<td id="bb"><input type="button" value="取得本TD裏面的ID" οnclick="getValue(this)" /></td>
</tr>
</table>
</body>
</html>
如上代碼,執行時彈出undefined,,只是因爲trElement.lastChild事實上並不能獲得<td id="bb"><input type="button" value="取得本TD裏面的ID" οnclick="getValue(this)" /></td>
這裏存在一個文本節點的概念,即是如果<td/><tr>和分開不在同一行的,那麼他們之間事實上還有文本節點,這裏trElement.lastChild取得的就是那個文本節點,而不是td節點,所以要把程序
<td id="bb"><input type="button" value="取得本TD裏面的ID" οnclick="getValue(this)" /></td>
</tr>
改成
<td id="bb"><input type="button" value="取得本TD裏面的ID" οnclick="getValue(this)" /></td></tr>
或者把
alert(trElement.lastChild.id);
改成
alert(trElement.lastChild.previousSibling.id); //取得那個文本節點後再取前一個兄弟節點
就能正常執行了,這裏是彈出 bb。