How can i check if a JavaScript-Eventhandler has been set?

前端 未结 3 1890
别跟我提以往
别跟我提以往 2020-12-14 18:54

I\'ve got a JavaScript-function that sets the \"onclick\"-event of some HTML-Nodes - even if that \"onclick\"-event has been set before.

How can i check if that ev

3条回答
  •  天涯浪人
    2020-12-14 19:32

    It should be possible to detect event handlers attached using .addEventListener() by intercepting calls to the function:

    var myListOfAddedEvents = [];
    
    var realAddEventListener = HTMLElement.prototype.addEventListener;
    
    HTMLElement.prototype.addEventListener = function(evtType,fn,cap) {
        myListOfAddedEvents.push(
            {on: this, type: evtType, handler: fn, capture: cap}
        );
    
        return realAddEventListener.apply(this, arguments);
    };
    

    Note: That is untested code and may need some work. I'm hoping this same function will be used by all element types, but I could be wrong. Also it will only work if you can run this bit of code before they start adding events. A copy for attachEvent could be constructed similarly.

提交回复
热议问题