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

Need help using Javascript to insert an onclick event

本文关键字:onclick 事件 帮助 插入 Javascript      更新时间:2023-09-26

我正在尝试在Google Analytics中使用事件跟踪。为了实现这一点,我需要为某些链接(我被要求跟踪的链接)添加一个onclick属性,如下所示:

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

我使用的CMS没有向菜单添加onclick事件的选项,我不想跟踪主导航中的每个链接。我对javascript只有初级的理解,但我一直在寻找一种方法,用它只将上面的onclick状态插入某些href值。

如有任何协助,我们将不胜感激。

或者,如果您想使用现有的trackOutboundLink函数,这将为所有指向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

您可能需要考虑使用回调hitCallback:重定向用户

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

您可以将GA send方法嵌入到onclick:中

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

这可能会像trackOutboundLink函数那样(假设您的示例基于此https://support.google.com/analytics/answer/1136920?hl=en)。

您的语法似乎没有什么问题,可能是引号造成了问题。

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