我正在尝试在点击特定按钮时向Google Analytics发送活动。
这是我的按钮ID:(#data_243342)
这是我的GA
脚本,可以点击上面的按钮。
onclick="dataLayer.push({"event": "eventGA","eventCategory" : "data1","eventAction" : "data-1-click","eventLabel" : "yes"})"
如何在jquery或javascript中传递此内容?
答案 0 :(得分:4)
有很多方法可以做到这一点:
使用Javascript:
(function() {
var button = document.getElementById("data_243342");
button.addEventListener("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
})();

<button id="data_243342" type="button">Send</button>
&#13;
使用jQuery:
$(function() {
$("#data_243342").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" type="button">Send</button>
&#13;
<强>更新强>
要添加具有相同功能的更多按钮,您可以尝试以下内容:
使用Javascript:使用document.getElementsByTagName
查找与该功能绑定的按钮。
(function() {
onload = function() {
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
}
};
})();
&#13;
<button id="data_243342" type="button">Send 1</button>
<button id="data_243343" type="button">Send 2</button>
<button id="data_243344" type="button">Send 3</button>
&#13;
使用jQuery:使用按钮的#id选择器。
$(function() {
// Set the buttons id in the jQuery function.
$("#data_243342, #data_243343, #data_243344").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" type="button">Send 1</button>
<button id="data_243343" type="button">Send 2</button>
<button id="data_243344" type="button">Send 3</button>
&#13;
更新:
jQuery中的另一种方法是使用类选择器。
$(function() {
// Every button with the btn-GA class can execute the function.
$(".btn-GA").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" class="btn-GA" type="button">Send 1</button>
<button id="data_243343" class="btn-GA" type="button">Send 2</button>
<button id="data_243344" class="btn-GA" type="button">Send 3</button>
&#13;
希望这有帮助。