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

前端 未结 7 1178
说谎
说谎 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:39

    how about setting oldClick = links[i].onclick or an empty function. Like so

    var oldOnClick = links[i].onclick || function() { return true; };
    
    links[i].onclick = function (e)
       {
           if (!oldOnClick())
               return false;
           //
           return true;
       }
    

    Or you could use attachEvent and addEventListener as others have recommended

    function addEvent(obj, type, fn) {
            if (obj.addEventListener)
                    obj.addEventListener(type, fn, false);
            else if (obj.attachEvent)
                    obj.attachEvent('on' + type, function() { return fn.apply(obj, [window.event]);});
    }
    

    and use like so

    addEvent(links[i], 'click', [your function here]);
    

提交回复
热议问题