简体   繁体   中英

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")
   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/

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);
}

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 eg 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. Ie

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

is the same as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM