How to add an onclick function to wordpress menu i

2019-07-29 23:11发布

I am setting up google analytics cross domain tracking on my website. I know I need to change each link to include:

onclick="_gaq.push(['_link', 'http://mywebsite.com/']); return false;"

I can set this up and get everything working great on the majority of the site, save one menu item. I've tried the jinMenu plugin, but that busted a few things.

site: http://www.trukid.com

Any help is much appreciated.

PS - This looks like it's on the right track for helping me, but I'm not sure how to translate it to my issue (I know minimal JS)

<script>

$(document).ready(function() {

    // Forcing WordPress to accept GA clicks

    $('.menu-twitter').delegate('a', 'click', function(e) {
        e.preventDefault();
        _gaq.push(['_trackEvent', 'Button', 'click', 'Twitter button']);  
        var lnk = $(this).attr('href');
        setTimeout('document.location = "' + lnk + '"', 100);
    });

    $('.menu-facebook').next.delegate('a', 'click', function(e) {
        e.preventDefault();
        _gaq.push(['_trackEvent', 'Button', 'click', 'Facebook button']);
        var lnk = $(this).attr('href');
        setTimeout('document.location = "' + lnk + '"', 100);
    });

});

</script>

1条回答
乱世女痞
2楼-- · 2019-07-30 00:00

For example:

<script>

$(document).ready(function() {
    $('#nav-main a ').click(function() {
    var p = $(this).attr('href');
    if (p.search(/.+mywebsite/) == -1){ 
        _gaq.push(['_link', 'http://mywebsite.com/']); return false;
    }       
    });
});

</script>

You don't need the "delegate" - that's necessary only when new links are created dynamically (links created via javascript have no events attached, delegate takes care of that). Replace nav-main with the id of your navigation an mywebsite with your domain.

The p.search bit makes sure that _link is only attached to the links that do not point to the domain the script runs on (since you need this only for links that go to your other domain).

查看更多
登录 后发表回答