[removed] Adding an onClick handler without overwriting the existing one

前端 未结 7 1156
说谎
说谎 2020-12-14 02:54

I\'m trying to modify all links on a page so they perform some additional work when they are clicked.

A trivial approach might be something like this:



        
相关标签:
7条回答
  • 2020-12-14 03:43

    This function should be usable (event listeners approach):

    function addEventListener(element, eventType, eventHandler, useCapture) {
        if (element.addEventListener) {
            element.addEventListener(eventType, eventHandler, useCapture);
            return true;
        } else if (element.attachEvent) {
            return element.attachEvent('on' + eventType, eventHandler);
        }
        element['on' + eventType] = eventHandler;
    }
    

    or you can save some more code adding this function (if you need to add the same event listener to many elements):

    function addClickListener(element) {
        addEventListener(element, 'click', clickHandler, false);
    }
    
    0 讨论(0)
提交回复
热议问题