2012-10-16 39 views
1

我想使用onclick函数将Google Analytics(分析)跟踪事件代码添加到提交按钮,但是那里已经有一个onclick函数。一个提交按钮中的两个onclick函数

现有代码

<input name="Submit" type="submit" class="button" style="float:left; clear:both;" onclick="MM_validateForm('name','','R','contact_number','','R','email','','RisEmail','address1','','R','address2','','R');return document.MM_returnValue" value="Submit" /> 

代码我想补充

onclick="_gaq.push(['_trackEvent', 'Contact Page Enquiry', 'Enquiry', 'Contact Page Enquiry']);" 

可以这样做?

回答

1

我只是猜测,但是...如果你只是在返回之前粘贴代码?

+1

谢谢,但我没有尝试,GA没有记录事件。 – user1016078

1

如果你正在使用jQuery它的作品。您可以在单个元素上有多个onclick事件。

检查this

代码

document.getElementById("a").onclick = function() { 
    alert(2); //this over writes the onclick on the element. This is called 
}; 

$("#a").click(function() { 
    alert(3); //this is called 
});​ 

HTML:

<a id="a" onclick="alert(1)">click</a>​ 

检查其他SO一样thisthis

从你上面的链接问题可以做这样的事情:

<input name="Submit" type="submit" class="button" style="float:left; clear:both;" onclick="MM_validateForm('name','','R','contact_number','','R','email','','RisEmail','address1','','R','address2','','R'); _gaq.push(['_trackEvent', 'Contact Page Enquiry', 'Enquiry', 'Contact Page Enquiry']); return document.MM_returnValue" value="Submit" /> 

这是未经测试的方式。

0

有两点需要注意:

  1. 你可能只是想如果表单通过验证的_trackEvent调用触发。
  2. 事件跟踪通过向分析服务器请求跟踪像素来工作。如果表单提交导致在跟踪请求完成之前将新页面加载到同一窗口,则最终可能会收集丢失或部分数据。

您可以通过延迟表单提交来解决第二个问题。

<input id="Submit" name="Submit" type="submit" ... /> 
... 
$('#Submit').click(function(e) { 
    // Prevent the default handling of the form submit button 
    e.preventDefault(); 
    MM_validateForm('name', ... 
    // If the form didn't validate, don't do anything else 
    if (!document.MM_returnValue) return; 
    _gaq.push(['_trackEvent', ... 
    // Get the form & submit it after 150ms delay 
    var form = $(this).parents('form:first'); 
    setTimeout(function() {form.submit()},150); 
});