javascript 兼容所有浏览器的DOM扩展功能(3)


<!DOCTYPE html>
<html lang="zh">
 <head>
  <title>DOM功能扩展</title>
 </head>
 <body>
    <a href="javascript:void(0)">你好</a>
    <script type="text/javascript">
        function DOMExtend(name, fn){
            if(typeof(HTMLElement)!="undefined"){
                eval("HTMLElement.prototype."+name+"="+fn);
            }
            else{
                var _getElementById=document.getElementById;
                document.getElementById=function(id){
                    var _elem=_getElementById(id);
                    eval("_elem."+name+"="+fn);
                    return _elem;
                }
                var _getElementByTagName=document.getElementsByTagName;
                document.getElementsByTagName=function(tag){
                    var _elem=_getElementByTagName(tag);
                    var len=_elem.length;
                    for(var i=0;i<len;i++){
                        eval("_elem["+i+"]."+name+"="+fn);
                    }
                    return _elem;
                }
                var _createElement=document.createElement;
                document.createElement=function(tag){
                    var _elem=_createElement(tag);
                    eval("_elem."+name+"="+fn);
                    return _elem;
                }
                var _documentElement=document.documentElement;
                eval("_documentElement."+name+"="+fn);
                var _documentBody=document.body;
                eval("_documentBody."+name+"="+fn);
            }
        }
        function BindEvent(event,fun){
            if(this.addEventListener){
                this.addEventListener(event,fun,false);
            }
            else{
                this.attachEvent("on"+event,fun);
            }
        }
        DOMExtend("bind",BindEvent);var wrap=document.getElementById("tagA");
        wrap.bind("click",function(){
            alert(this.innerHTML);
        })
    </script>
 </body>
</html>


OK,目前为止已经解决了兼容性问题,这是所有浏览器都能顺利通过的DOM元素扩展的代码,但是这样还有一个小问题,细心的人会发现在IE浏览器里面弹出的结果是"undefined",而不是"你好";问题的原因在于IE的事件绑定上,看以上代码,当调用alert(this.innerHTML)的时候,由于IE绑定事件用的是attachEvent,这时候this指向的是windows,于是现在的目标的要改变this指向的对像,将this指向tagA。于是经过修改,完整代码如下:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wddpfs.html