![](/img/trans.png)
[英]Google adwords conversion tracking - How to track 2 different onclick conversions on same page?
[英]Using js to fire an onclick event from a button (to track google adwords conversions)
我有一个网站,我正在尝试使用 Google Adwords 设置转化。 我已经设置了全局标签,我正在尝试使用 js 单击按钮时触发 onclick 事件。
下面的代码是我的解决方案。 但是,查看开发人员工具时,我没有看到 console.log 着火,所以很明显有故障。
我在这里做错了什么?
该按钮具有以下代码:
<button class="button primary" type="submit">
我的js:
<script>
document.getElementsByClassName("button").onclick = function() {myFunction()};
function myFunction() {
return "gtag_report_conversion(‘https://www.somesite.com')";
console.log(hello);
}
</script>
除了@Dave 提到的elementsByClassName 问题-您在控制台日志之前返回gtag 字符串-这意味着您永远不会看到日志-以及控制台日志中的hello 需要引号作为字符串-否则它将被解释为一个可变名称 - 您没有在代码中定义。
我已经更新在按钮上有一个 eventListener - 请注意 [0] 这是由于 Dave 正在重新考虑的问题 - 这会将侦听器添加到返回的节点列表中的第一个按钮。
请注意,您仍将使用 ClassName 选择器获得一组元素 - 即使只有一个 - 因此您需要指示 [0] 的索引以定位数组中的该项目。
编辑 - 更新为使用 querySelector
document.querySelector(".button").addEventListener('click', ()=> myFunction()); function myFunction() { console.log("hello"); return "gtag_report_conversion('https://www.somesite.com')"; }
<button class="button primary" type="submit">Click me </button>
我们来分析一下——请阅读代码中的注释:
function myFunction() {
return "gtag_report_conversion(‘https://www.somesite.com')";
//the line above will just return a string which will finish the execution of this function
console.log(hello);
//this will not run as we have returned
//btw, is this a variable you want to output or just a string?
}
你不想要这个吗?:
function myFunction() {
gtag_report_conversion(‘https://www.somesite.com');
//this should log the conversation, no need to return it's value
console.log('hello');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.