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

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 46 ::
收藏到网摘: 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>