请问 javascript 怎样获取已绑定事件?

JavaScript07

请问 javascript 怎样获取已绑定事件?,第1张

<!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>

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

望采纳!

直接用js

document.getElementById(id).onclick=function(){}//内容写在函数体里

或者用jquery

$("#a").click(function(){ })

想必大家都有遇到过,DOM动态添加的元素,你给它绑定的事件是不起作用的。目前有两种办法,为动态添加的元素绑定事件

⚠️ 动态添加的子元素一定要放在on()方法里面,并且on()方法里面的 childSelector 必须要是 selector 的子元素,否则动态添加的元素绑定的事件依旧无效