简体   繁体   English

Google Analytics(分析)事件跟踪:按钮监听器不起作用

[英]Google Analytics Event Tracking: button listener does not work

I need to add an event handler for GA event tracking to a button. 我需要将用于GA事件跟踪的事件处理程序添加到按钮。 I read the documentation thoroughly and spent an hour googling, but I didn't make it work. 我仔细阅读了文档并花了一个小时的时间来搜寻,但是我没有使它起作用。 The session tracking works (I see myself in realtime analytics), but the event tracking doesn't work. 会话跟踪有效(我在实时分析中看到了自己),但是事件跟踪不起作用。 This is my code: 这是我的代码:

<html>
<head>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-12345678-1', 'auto');
  ga('send', 'pageview');
</script>
</head>

<body>
<div>
<script>
var downloadLink = document.getElementById('submit_btn');
addListener(downloadLink, 'click', function() {
  ga('send', 'event', 'button', 'click', 'nav-buttons');
});
function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>
<button type="submit" id="submit_btn" name="submit_btn">submit</button></div>
</body>
</html>

What am I doing wrong here? 我在这里做错了什么?

I am not sure, but it may be the way the JavaScript code is invoke on the page.Can you try the following code: 我不确定,但这可能是在页面上调用JavaScript代码的方式。您可以尝试以下代码:

<body>
  <div>
    <button type="submit" id="submit_btn" name="submit_btn">submit</button>
  </div>  
</body>
<script>
  var downloadLink = document.getElementById('submit_btn');

  addListener(downloadLink, 'click', function() {
    ga('send', 'event', 'button', 'click', 'nav-buttons');
  });

  function addListener(element, type, callback) {
    if (element.addEventListener) element.addEventListener(type, callback);
    else if (element.attachEvent) element.attachEvent('on' + type, callback);
  }
</script>
</html>

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

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