[英]Two onclick functions in one submit button
我想使用onclick功能將Google Analytics跟蹤事件代碼添加到提交按鈕,但是那里已經有一個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']);"
可以這樣做嗎?
您需要一個回調函數,它將在單擊事件中觸發兩個腳本。
我只是猜測,但是...如果你在返回之前粘貼代碼怎么辦?
如果您正在使用jQuery,它可以工作。 您可以在單個元素上擁有多個onclick事件。
檢查一下
碼
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>
從上面的鏈接,你可以做這樣的事情:
<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" />
這是未經測試的方式。
有兩點需要注意:
_trackEvent
調用。 您可以通過延遲表單提交來解決第二個問題。
<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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.