簡體   English   中英

一個提交按鈕中有兩個onclick功能

[英]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']);"

可以這樣做嗎?

您需要一個回調函數,它將在單擊事件中觸發兩個腳本。

http://jsfiddle.net/gF7Td/2/

我只是猜測,但是...如果你在返回之前粘貼代碼怎么辦?

如果您正在使用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" />

這是未經測試的方式。

有兩點需要注意:

  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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM