$(document).ready(function(){
$('#commentform').submit(function(){
var postname = $('h2.post-title').text();
ga('send', 'event', 'Engagement', 'Comment', postname, 5);
});
});
首先。此代码将h2
标记的文本与document
中的post-title
类别相关联。一种更可靠的方式来获得该职位的标题将是一个ID。
其次,它可能无法正常工作,因为表单在Google Analitycs代码触发前被提交。因此,您应该停止默认行为并在analitycs完成发送数据后提交表单。 (参见:https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback)
$(document).ready(function() {
$(document).on('submit', 'form#commentform', function(e) {
var postname = $('#post-title').text();
ga('send', {
'hitType': 'event',
'eventCategory': 'Engagement',
'eventAction': 'Comment',
'eventLabel': postname,
'eventValue': 5,
'hitCallback': function() {
//now you can submit the form
//$('#commentform').off('submit').trigger('submit');
$('#commentform').off('submit'); //unbind the event
$('#commentform')[0].submit(); //fire DOM element event, not jQuery event
}
});
return false;
});
});
编辑: 我才意识到从hitCallback
代码可能无法正常工作。修改后的版本应该调用DOM元素的事件并在结果中发送表单。
EDIT2: 修正对象事件的情况下,结合时的document.ready()被触发GA(...)后
回报虚假的形式不存在; – ElSinus 2013-04-23 12:01:33
你有什么错误?什么是问题?只是不工作? – 2013-04-23 12:03:04
我认为问题在于页面正在刷新 – 2013-04-23 12:04:39