js 判断是否存有事件 addeventlistener

JavaScript017

js 判断是否存有事件 addeventlistener,第1张

原生实现无法判断是否有事件。如果确实需要请参照以下代码,另外本代码只使用于调用dom2形式加载或者移除事件功能,对应dom0类型的没有做测试。

以下代码修改了原生的Element对象,是否需要这样做,请自己酌情处理。

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title></title>

    <script type="text/javascript">

        /**

         * 此处代码必须放到任何javascript代码之前。另外增加事件只能用addEventListener形式。

         */

        (function() {

            Element.prototype.eventListenerList = {}

            Element.prototype._addEventListener = Element.prototype.addEventListener

            Element.prototype._removeEventListener = Element.prototype.removeEventListener

            Element.prototype.addEventListener = function(a,b,c) {

                this._addEventListener(a,b,c)

                if(!this.eventListenerList[a]) this.eventListenerList[a] = []

                this.eventListenerList[a].push(b)

            }

            Element.prototype.removeEventListener = function(a,b,c){

                this._removeEventListener(a, b,c)

                if(this.eventListenerList[a]){

                    var arr = this.eventListenerList[a]

                    for(var i =0i<arr.lengthi++){

                        if(arr[i].toString() === b.toString()){

                            this.eventListenerList[a].splice(i,1)

                        }

                    }

                }

            }

        })()

        //此后为测试代码。

        window.onload = function(){

            var dom = document.getElementById("test")

            //增加三个监听

            dom.addEventListener("click",function(){

                console.info("click function")

            },false)

            dom.addEventListener("click",function(){

                console.info("click function2")

            },false)

            dom.addEventListener("click",function(){

                console.info("click function3")

            },false)

 

            console.log(dom.eventListenerList["click"].length)

            //读出监听的方法

            var clicks = dom.eventListenerList.click

            if(clicks) clicks.forEach(function(f) {

                console.log("I listen to this function: "+f.toString())

            })

            //删除监听

            dom.removeEventListener("click",function(){

                console.info("click function")

            },false)

             

            console.log(dom.eventListenerList["click"].length)

        }

    </script>

</head>

<body>

    <button id="test" >测试</button>

</body>

</html>

<button onclick="test()">TEST</button>

<script>

function test(){

   if(event&&event.target==event.currentTarget){

      console.log("本函数是由鼠标点击事件触发的")

   }else{

      console.log("本函数是由js代码调用的")

   }

}

test()

</script>