[removed] Adding an onClick handler without overwr

2020-02-08 06:31发布

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:

function adaptLinks()
{
    var links = document.getElementsByTagName('a');
    for(i = 0; i != links.length; i++)
    {
        links[i].onclick = function (e)
        {
            <do some work>
            return true;
        }
    }
}

But some of the links already have an onClick handler that should be preserved. I tried the following:

function adaptLinks()
{
    var links = document.getElementsByTagName('a');
    for(i = 0; i != links.length; i++)
    {
        var oldOnClick = links[i].onclick;
        links[i].onclick = function (e)
        {
            if(oldOnClick != null && !oldOnClick())
            {
                return false;
            }
            <do some work>
            return true;
        }
    }
}

But this doesn't work because oldOnClick is only evaluated when the handler is called (it contains the value of the last link as this point).

7条回答
贼婆χ
2楼-- · 2020-02-08 07:02

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;
       //<do some work>
       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]);
查看更多
登录 后发表回答