[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 06:42

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);
}
查看更多
Summer. ? 凉城
3楼-- · 2020-02-08 06:42

I had problems with overloading in the simple way - this page was a great resource http://www.quirksmode.org/js/events_advanced.html

查看更多
你好瞎i
4楼-- · 2020-02-08 06:47

Use a wrapper around addEventListener (DOM supporting browsers) or attachEvent (IE).

Note that if you ever want to store a value in a variable without overwriting the old value, you can use closures.

function chain(oldFunc, newFunc) {
  if (oldFunc) {
    return function() {
      oldFunc.call(this, arguments);
      newFunc.call(this, arguments);
    }
  } else {
    return newFunc;
  }
}

obj.method = chain(obj.method, newMethod);

In Aspect Oriented Programming, this is known as "advice".

查看更多
霸刀☆藐视天下
5楼-- · 2020-02-08 06:52

Don't assign to an event handler directly: use the subscribe model addEventListener / attachEvent instead (which also have remove pairs!).

Good introduction here.

查看更多
甜甜的少女心
6楼-- · 2020-02-08 06:59

Using JQuery, the following code works:

function adaptLinks(table, sortableTable)
{
    $('a[href]').click(function (e)
    {
        if(!e.isDefaultPrevented())
        {
            <do some work>
        }
    });
}

This requires using an extra library but avoids some issues that exist with addEventListener/attachEvent (like the latter's problem with this references).

There is just one pitfall: if the original onClick handler is assigned using "normal" JavaScript, the line

...
if(!e.isDefaultPrevented())
...

will always resolve to true, even in case the original handler canceled the event by returning false. To fix this, the original handler has to use JQuery as well.

查看更多
爷的心禁止访问
7楼-- · 2020-02-08 07:01

You need to create a closure to preserve the original onclick value of each link:

<a href="#" onclick="alert('hi');return false;">Hi</a>
<a href="#" onclick="alert('there');return true;">There</a>
<script type="text/javascript">
function adaptLinks() {
    var links = document.getElementsByTagName('a');
    for (i = 0; i != links.length; i++) {
        links[i].onclick = (function () {
            var origOnClick = links[i].onclick;
            return function (e) {
                if (origOnClick != null && !origOnClick()) {
                    return false;
                }
                // do new onclick handling only if
                // original onclick returns true
                alert('some work');
                return true;
            }
        })();
    }
}
adaptLinks();
</script>

Note that this implementation only performs the new onclick handling if the original onclick handler returns true. That's fine if that's what you want, but keep in mind you'll have to modify the code slightly if you want to perform the new onclick handling even if the original handler returns false.

More on closures at the comp.lang.javascript FAQ and from Douglas Crockford.

查看更多
登录 后发表回答