开发者

onclick not firing for download

开发者 https://www.devze.com 2023-01-05 02:31 出处:网络
Im having trouble with a onclick event for a download. It does not want to fire when I click on the link. It just carries on as normal. But it does work with an external link. Have I done something ob

Im having trouble with a onclick event for a download. It does not want to fire when I click on the link. It just carries on as normal. But it does work with an external link. Have I done something obviously wrong?

<a href="http://www.wildlifetrusts.org/" target="_blank" onclick="trackExternalLink(this, '/links-the_royal_society_of_wildlife_trusts');">Royal Society of Wildlife Trusts.</a>
<a href="/c2/uploads/our strategy for 2010_15.pdf" target="_blank" onclick="trackExternalLink(this, '/downloads-our_strategy_for_2010-15');">2010-2015 strategy,</a>

Its doing the same in FF, Chrome and IE 8.

function trackExternalLink(link, action) {
_gaq.push(['_trackPage开发者_如何转开发view', action]);
setTimeout('document.location = "' + link.href + '"', 25000)
return false;
}


You're not returning false from your onclick handler. You're returning false from the function it calls, but then throwing that away in the handler. You meant:

onclick="return trackExternalLink(this, '/links-the_royal_society_of_wildlife_trusts');"

However all this onclick stuff is pretty ugly. Consider unobtrusive scripting. And lose the nasty call to setTimeout creating script from a string. Do Google really recommend this code? It kinda sucks.

Here's a quick hack version that wraps the action into a class name:

<a href="http://www.wildlifetrusts.org/" class="ping-links-the_royal_society_of_wildlife_trusts">Royal Society of Wildlife Trusts.</a>

<script type="text/javascript">
    for (var i= document.links.length; i-->0;)
        if (document.links[i].className.substring(0, 5)==='ping-')
            document.links[i].onclick= pingclick;

    function pingclick() {
        var action= this.className.substring(5);
        var href= this.href;

        _gaq.push(['_trackPageview', action]);
        setTimeout(function() {
            location.href= href;
        }, 25000);

        return false;
    }
</script>

This still isn't great. 25 seconds (25000) is obviously way too long a delay; you probably want to pull that down to around 200ish. Really it should be following the link as soon as the XMLHttpRequest that passes the information to the server is complete, rather than using an arbitrary delay, but Google don't seem to give you that option. How poor. Then again, link-tracking pingback scripts are a nasty, user-hostile activity anyway.


I believe you need to return false to prevent the click from functioning as normal, this may, however, be jQuery specific.

I would also recommend using a framework rather than onclick attributes, they're messy and the framework will also be helpful in other respects.

0

精彩评论

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