I haven't tested this in a full production environment, but this little snippet of jQuery seems to be giving me a good way to parse links with customizable class names into an equivalent google analytics events tracking code.
我没有在完整的生产环境中测试过这个,但是这个jQuery的小片段似乎给了我一个很好的方法来解析具有可自定义类名的链接到一个等效的谷歌分析事件跟踪代码。
Does this work well for you? Anything I could be doing better here?
这适合你吗?我能在这里做得更好吗?
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){}}
});
2 个解决方案
#1
1
I wrote this thingy and have been using it for all my event tracking:
我写了这个东西,并一直用它来进行我的所有事件跟踪:
#2
1
Seems like a reasonable way to go about it. If it works for you go with it.
似乎是一种合理的方式来解决它。如果它适合你,那就去吧。
#1
1
I wrote this thingy and have been using it for all my event tracking:
我写了这个东西,并一直用它来进行我的所有事件跟踪:
#2
1
Seems like a reasonable way to go about it. If it works for you go with it.
似乎是一种合理的方式来解决它。如果它适合你,那就去吧。