当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 解决使用attachEvent函数时,this指向被绑定的元素的问题的方法

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 解决使用attachEvent函数时,this指向被绑定的元素的问题的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 42 ::
收藏到网摘: n/a

使用attachEvent对同一事件进行多次绑定,这是解决事件函数定义冲突的重要方法。但是在IE中,函数内的this指针并没有指向被绑定元素,而是function对象,在应用中,这是很难受的一件事,如果试图用局部变量传送元素,会因为闭包而引起内存泄漏。那么,我们应该如何解决这一难题呢?
我给Function添加了原型方法“bindNode”,在这个方法里,根据传送过来的元素,进行全局性存储转换,然后返回经过封装的函数,使用call方法来进行属主转换。

<html>
<body>
<button id=btTest>test</button>
</body>
</html>
<script>
if(!document.all){
HTMLElement.prototype.attachEvent=function(sType,foo){
this.addEventListener(sType.slice(2),foo,false)
}
}
Function.prototype.bindNode=function(oNode){
var foo=this,iNodeItem
//使用了全局数组__bindNodes,通过局部变量iNodeItem进行跨函数传值,如果直接传送oNode,也将造成闭包
if(window.__bindNodes==null)
__bindNodes=[]
__bindNodes.push(oNode)
iNodeItem=__bindNodes.length-1
oNode=null
return function(e){
foo.call(__bindNodes[iNodeItem],e||event)
}
}
abc()
function abc(){
var bt=document.getElementById("btTest")
bt.attachEvent("onclick",function(){
//如果不经过bindNode处理,下面的结果将是undefined
alert(this.tagName)
}.bindNode(bt))
bt=null
}
</script>