简体   繁体   English

Google Analytics(分析):添加了onClick,但是链接已经具有onClick吗?

[英]Google Analytics: adding onClick, but link already has onClick?

I'm using Google Analytics (Universal) and I'm trying to add the onClick action to a link, but there's already onClick script in place: 我正在使用Google Analytics(分析)(通用),并且试图将onClick操作添加到链接中,但是已经有onClick脚本了:

<a class="checkout-btn" href="/checkout-start" class="button_control" onclick="return $(this).getForm().sendRequest('shop:on_setCouponCode')">Check out</a>

But I need to add this script for GA: 但是我需要为GA添加此脚本:

onClick="ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools');" onClick =“ ga('send','event','Header','hover','Outdoor Barstools');”

How can I get two onClick events on one link? 如何在一个链接上获得两个onClick事件? Is it possible? 可能吗?

The easiest (although wrong) way is to use a semi colon, having two commands: 最简单(尽管错误)的方法是使用半冒号,它有两个命令:

onClick="ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools'); return $(this).getForm().sendRequest('shop:on_setCouponCode')"

The better way would be to never use the onClick HTML attribute and use an external JavaScript file to bind to the click() event of the ID. 更好的方法是永远不要使用onClick HTML属性,而使用外部JavaScript文件绑定到ID的click()事件。 This improves code maintainability. 这样可以提高代码的可维护性。

Tag becomes: 标签变为:

<a class="checkout-btn" id="foo" ...

Using jQuery, and referencing the ID 'foo' tag: 使用jQuery,并引用ID'foo'标签:

$('#foo').click(function() {
    ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools');
    return $(this).getForm().sendRequest('shop:on_setCouponCode');
});

This is one of the reasons why adding a handler directly in the HTML is sub-optimal. 这是为什么直接在HTML中添加处理程序的效果欠佳的原因之一。 If you are using jQuery, you could use the bind method, for example: 如果使用的是jQuery,则可以使用bind方法,例如:

$(".checkout-btn" ).bind( "click", function(evt) {
       console.log('oh yeah');         
});

If you are just using raw JavaScript, it's something like this: 如果您仅使用原始JavaScript,则如下所示:

document.getElementById("checkout-btn")
        .addEventListener("click", function(evt) {
       console.log('oh yeah');         
}, false);

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

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