本來以為用$(this)可以很容易獲得當前點擊的對象,可在用的時候,發現並沒有想象的那么簡單。$(this)獲取的是[object Object],並不能用jquery的方法去尋找當前對象的前后節點。代碼如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function launch(){
var a=$().parent().prev().children(":eq(0)").val();
alert(a);
}
</script>
</head>
<body>
<table>
<tr>
<td><input type="text" value="還是這里"/></td>
<td></td>
</tr>
<tr>
<td><input type="text" value="這里"/></td>
<td><a onclick="launch()">點擊</a></td>
</tr>
</table>
</body>
</html>
代碼執行的效果是:
將代碼做如下改動:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function launch(a,b){
var a=$(a).parent().prev().children(":eq(0)").val();
alert(a);
}
</script>
</head>
<body>
<table>
<tr>
<td><input type="text" value="還是這里"/></td>
<td></td>
</tr>
<tr>
<td><input type="text" value="這里"/></td>
<td><a onclick="launch(this,event)">點擊</a></td>
</tr>
</table>
</body>
</html>
則代碼的執行效果:
就可以獲取當前點擊的對象。
該方法就可以非常方便的獲取點擊對象和點擊對象相關的節點。