简体   繁体   中英

jQuery/Javascript: How to get anonymous function to reference variable declare outside?

I have some jQuery code that doesn't work as expected.

$('a[href^="http://"]').not('[href^="http://mydomain.com"], [href^="http://itunes.apple.com"]').click(function (e) {
    e.preventDefault();
    console.log("external: " + this.getAttribute('href'));
    var url = this.getAttribute('href');
    foo.track(
        "External", 
        { 'URL': url }, 
        function (url) { 
            location.href = url 
        }
    );
});

For this example, I'm tracking all external clicks from my domain, except for iTunes apps store. Assume foo.track() is a 3rd party method I'm using to track some events for reporting. The last parameter to it is an anonymous function that is executed once the tracking call successfully returns.

The code above is trying to navigate everything to http://mydomain.com/1 for some reason. However, the console.log statement succesfully logs the expected values. It's as if the url variable isn't referencing the value I expect. I've also tried replacing location.href = url with window.location = url but I get the same result.

What am I doing wrong?

Just remove the parameter from the navigation function. Like this:

$('a[href^="http://"]').not('[href^="http://mydomain.com"], 
                             [href^="http://itunes.apple.com"]').click(function (e) {
e.preventDefault();
console.log("external: " + this.getAttribute('href'));
var url = this.getAttribute('href');
foo.track("External", { 'URL': url }, function (/*url*/) { location.href = url });
});

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