在處理嵌套結構時,往往需要從當前元素向上查找最近的某個父節點。jQuery 提供的 closest() 方法正是為此而生,本文以查找最近的 table 為例進行演示。
<html>
<head>
<title>usually function</title>
</head>
<body>
<table name="name_table1">
<tr><td>table1</td></tr>
</table>
<table name="name_table2">
<tr><td>table2</td></tr>
</table>
<table name="name_table3">
<tr><td>table3</td></tr>
</table>
</body>
<html>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script>
$(function(){
$("td").bind("click",function(){
alert($(this).closest("table").attr("name"));
});
});
</script>
這裡點擊任意 td 時,closest("table") 會從當前 td 向上查找最近的 table 祖先元素,再透過 attr("name") 取得它的 name 屬性,从而精准定位到所屬的表格。
希望這個查找最近父節點的方法對大家有所幫助。