JavaScript中的this

JavaScript中的this


一网友问了个问题

<tr><td><a href="javascript:find(this)">点击</a></td></tr>
找td怎么找?
function find(obj){
   alert($(obj).parent());
}
这样不行呀

群空间测试之后发现是可以的:

$('a:contains(关于腾讯公司整治低俗内容的公告)') .parent().parent() .html()
' <div><a href="http://qun.qq.com/air/#announce" target="_blank">关于腾讯公司整治低俗内容的公告</a></div> <div>Copyright © 1998 - 2011 Tencent. All Rights Reserved</div>
<div>腾讯公司 版权所有</div> '

仔细观察他的代码,发现处理事件是写在href中的,通过下面的代码可以知道

<a href="javascript:alert('this === window:' + (this === window))">this === window</a>
<a href="javascript:;" onclick="alert('this.tagName:' + (this.tagName));return false;">tagName</a>

this === window tagName

这时候的this是window,当然找不到parent啦。

最后有网友说,像这样的代码:

<a href="javascript:void 0;" onclick="editRole('${rls.roleFix}',this)">编辑</a>

改成↓

<a href="javascript:;" onclick="editRole('${rls.roleFix}',this)">编辑</a>

理由是:这样写比void(0)好,void(0)后onclick事件不启作用的

这说法不知对不对,有待验证

不积跬步无以至千里

不积小流无以成江海

2011年5月18日

阿良

原文地址:https://www.cnblogs.com/itelite/p/2217062.html