最近写代码的时候碰到一个问题:
<script src="jquery-1.7.1.js"></script>
<script>
function test(){
var idd = $(this).attr('id');
alert(idd);
var Tr1 = $("td").parent();
alert(Tr1.attr('id'));
}
</script>
<body>
<table border="1px">
<tr id="testTr">
<td id="testTd" οnclick="test()" width="80px">ts</td>
</tr>
</table>
</body>
以上代码,在alert(idd)时,无法获取到我想要的属性值:id;
最后在调试js时发现该this对象是一个window对象,也就是说,这个this指向的不是函数的调用者,而是这个 <script>标签的对象。因此获取id时显示为undefined。
将代码修改为:
<script src="jquery-1.7.1.js"></script>
<script>
function test(o){
var idd = $(o).attr('id');
alert(idd);
var Tr1 = $("td").parent();
alert(Tr1.attr('id'));
}
</script>
<body>
<table border="1px">
<tr id="testTr">
<td id="testTd" οnclick="test(this)" width="80px">ts</td>
</tr>
</table>
</body>
此时 test(this) 中的this才是我想要获取到的对象。