简体   繁体   English

需要使用Javascript插入onclick事件的帮助

[英]Need help using Javascript to insert an onclick event

I am attempting to use Event tracking in Google Analytics. 我正在尝试在Google Analytics(分析)中使用事件跟踪。 In order to achieve this I need to add an onclick attribute to certain links (The ones I was asked to track) like so: 为了实现这一点,我需要向某些链接(要求我跟踪的链接)添加onclick属性,如下所示:

<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com');  return false;">Check out example.com</a>

The CMS I am using does not have an option to add onclick events to the menu and I don't want to track every link in the main navigation. 我正在使用的CMS没有将onclick事件添加到菜单的选项,并且我不想跟踪主导航中的每个链接。 I only have a beginner's level understanding of javascript, but I have been looking for a way to use it to insert the onclick status above to only certain href values. 我对javascript只是一个初学者的了解,但是我一直在寻找一种使用它的方法将上述onclick状态仅插入某些href值。

Any assistance would be greatly appreciated. 任何帮助将不胜感激。

Alternatively, if you would like to use your existing trackOutboundLink function, this would attach a click event to all outboud links going to http://www.example.com : 另外,如果您想使用现有的trackOutboundLink函数,这会将click事件附加到所有前往http://www.example.com的出站链接:

$(function() {
  // adding onclick event to this particular link
  $('a[href="http://www.example.com"]').click(function(event) {
    // preventing the user from navigating away from the page, temporarily
    event.preventDefault();
    // GA tracking
    trackOutboundLink('http://www.example.com');
    // continue default behavior for the click
    window.location = 'http://www.example.com';
  }); // end click event
}); // end document ready

You may want to consider redirecting the user using the callback hitCallback: 您可能要考虑使用回调hitCallback重定向用户:

ga('send', {
            'hitType': 'event',
            'eventCategory': '...',
            'eventAction': '...',
            'eventLabel': '...',
            'hitCallback': function(){
                // redirect:
                window.location = 'http://www.example.com';
            }
        }

You can embed the GA send method into the onclick: 您可以将GA send方法嵌入onclick中:

onclick="ga('send','event','outbound','click','http://www.example.com');"

This would likely do what the trackOutboundLink function does (assuming you were basing your example from this https://support.google.com/analytics/answer/1136920?hl=en ). 这很可能会完成trackOutboundLink函数的功能(假设您是基于https://support.google.com/analytics/answer/1136920?hl=zh_CN的示例)。

您的语法似乎没有问题,可能是引起问题的引号。

<a href="http://www.example.com"  onclick=" trackOutboundLink('http://www.example.com'); return false; ">Check out example.com</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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