开发者

Why does the onclick function run on onclick, but not when I call it manually?

This is my code

 // Register onclick
 var old_onclick = link.onclick;

 link.onclick = function() {
  astr_track_action(param);

  if(typeof(old_onclick) == "function开发者_StackOverflow")
   old_onclick();
 }

And this is the html

<a onclick="alert('hello!');" href="http://www.google.com?acme=link&foo=bar">To google!</a>

When I click the link, the alert pops up. But when I override the onclick with my JS code, the alert does not pop up.

Any ideas?


Edit: I just want to add, I have debugged and confirmed that old_onclick() is run, but no alert message shows up.


Edit: Here is the full code from the loop start. I don't see how it's relevant, but it was requested:

for(var i = 0; i < document.links.length; i++)
{
    var link = document.links[i];
    var eventlink = link.href.split("acme=");

    if(eventlink.length > 1)
    {
        var param = eventlink[1].split("&")[0];
        var newlink = link.href;

        // Register onclick
        var old_onclick = link.onclick;

        link.onclick = function() {
            astr_track_action(param);

            if(typeof(old_onclick) == "function")
                old_onclick();
        }


This should work as expected:

example: http://www.jsfiddle.net/8RJ5y/


You are creating functions in a loop. old_onclick will point to the click handler of the last element you loop over (because upon execution, the click handlers will access old_onclick when the loop already finished).
You have to capture the value by e.g. using an immediate function:

var old_onclick = link.onclick;

link.onclick = (function(old_onclick) {
    return function() {
        astr_track_action(param);

        if(typeof(old_onclick) == "function")
                 old_onclick();
        }
    };
 }(old_onclick));

JavaScript has no block scope, only function scope. I.e.

for(...) {
    var foo = something;
}

is the same as

var foo;
for(...) {
    foo = something;
}


It does work, so far as I can tell: jsfiddle

Note that, if you are doing anything using this, you will need to use apply, rather than just invoking the function normally:

if (typeof(old_onclick) == 'function') {
    old_onclick.apply(this, arguments);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜