我尚未在完整的生产环境中对此进行过测试,但是jQuery的这一小片段似乎为我提供了一种将具有可自定义类名的链接解析为等效的Google Analytics(分析)事件跟踪代码的好方法。
这对您有用吗?我在这里能做得更好吗?
jQuery(function(){
$("a.track").each(function(){
var obj = $(this); //provide scope
obj.data("href", obj.attr("href"));
obj.data("target", obj.attr("target"));
obj.attr({"target": ""});
obj.attr({"href": "#" + obj.data("href") });
obj.click(function(){
var find = {c: "cat_", a:"action_", l:"label_", d:"data_"}; //define your class prefixes
var p = {};
$.each(obj.attr('class').split(/\s+/), function(i,v){
$.each(find, function(a, b){
if(v.indexOf(b) == 0){ p[a] = v.replace(b, "").replace("__", " "); } //double underscore converted to space
});
});
track(p); Log("tracking...");
if(obj.data('target') == "_blank"){
var newWindow = window.open(obj.data("href"), '_blank');
newWindow.focus();
}
else{ window.location = obj.data("href");
}
});
});
function track(i){
if(i==undefined || !i["c"] || !i["a"]){Log("Both the 'category' and 'action' are required to track events!"); return;}
var d = {c: "Category", a:"Action", l:null, d:null}; //set default values
var p = $.extend(d, i); //merge function data with defaults
_gaq.push(['_trackEvent', p.c, p.a, p.l]);
}
function Log(x){try{console.log(x);}catch(e){}}
});
最佳答案
我写了这个东西,并一直用于我的所有事件跟踪:
https://github.com/spilliton/track_that