我需要为按钮添加GA事件跟踪的事件处理程序。我彻底阅读了文档并花了一个小时谷歌搜索,但我没有让它工作。 会话跟踪工作(我在实时分析中看到自己),但事件跟踪不起作用。 这是我的代码:
<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>
我在这里做错了什么?
答案 0 :(得分:2)
我不确定,但它可能是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>