JavaScript中removeEventListener()使用注意事项

最近复习JavaScript中的基础知识,一方面给新来的实习生介绍一下JavaScript基础知识,一方面也是自己工作一年来自己在JavaScript方面学习的总结。

 

Javascript在Web开发中地位越来越重要,所以也很多人说,JavaScript在Web开发中地位就像C语言在操作系统上的地位。目前稍微复杂的Web应用或者企业拥有,都会使用到JavaScript。

 

addEventListener(eventtarget,eventlistener,event caputring)

设计demo的需求是,页面放置一个button。当用户点击button按钮时,对button添加事件,然后在handler处理函数里面,使用removeEventListener()移除刚刚绑定的事件。

<html>
    <head>
    </head>
    <body>
        <input id="info"  type="button" value="Click Me!" />
    <script type="text/javascript">
    
        var target=document.getElementById('info');
        target.addEventListener('click',function(){
            console.log("I have been clicked!");
            
            target.removeEventListener('click',function(){
                console.log("removing the click event!");
            },false);
        },false);
        
    </script>
    </body>
</html>

 

实验结果是,用户点击button时,每次都会输出"I have been clicked!",说明removeEventListener()函数没有起到作用。通过查找资料,得出结论。在使用removeEventListener()函数时,handler函数,必须和使用addEventListener()里面的handler函数必须相同。所以上面写的代码是错误的。修正之后的代码应该如下:

<html>
    <head>
    </head>
    <body>
        <input id="info"  type="button" value="Click Me!" />
        <script type="text/javascript">
            //addEventListener()和removeEventListener()中handler函数必须相同,移除事件函数才有效。
            function myhandler(){
                console.log("I have been clicked!");
                document.getElementById('info').removeEventListener('click',myhandler,false);
            }
            var target=document.getElementById('info');
            target.addEventListener('click',myhandler,false);
            
        </script>
    </body>
</html>

 

参考网址:http://www.html5china.com/js/jsbase/20111124_2904.html

目前开发中大多数开发人员会使用常用一种JavaScript类库,比如jQuery,YUI,Prototype等等,所以也不需要考虑IE浏览器和其他支持标准DOM事件浏览器在处理事件不同方法。

地图图片

 

(测试一下Bing地图)

posted @ 2012-08-21 23:21  快乐八哥  阅读(12913)  评论(0编辑  收藏  举报