簡體   English   中英

使用 HTML 中的提交按鈕調用函數

[英]Call a function with the submit button in HTML

每當有人提交免費報價表格時,我都需要一個 Google AdWords 轉換腳本才能工作。 谷歌提供了腳本,我用 WordPress 將其放入片段並為該站點激活它。

我現在需要在按下提交按鈕時調用該函數,但我不記得正確的語法,到目前為止,Google 搜索已經讓我找到了長長的 .php 文件創建路徑,這些路徑並沒有回答感覺像是一個簡單的解決方案會解決的。

目前我已經根據提交的現有代碼添加了該功能,但我不相信這是正確的。 以下代碼位於頁面使用的聯系表單上。

[submit id:submit class:btn class:btn-primary gtag_report_conversion() "Send"]

下面是我放入 Snippet 的代碼減去完整的“發送到”AW 地址:

<script>
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  };
  gtag('event', 'conversion', {
      'send_to': 'AW-.....',
      'event_callback': callback
  });
  return false;
}
</script>

根據該短代碼的實現方式,很可能您不能像那樣向它添加內聯事件處理程序——而且如果沒有看到源代碼就很難確定(但我敢打賭,這很可能是這種情況)。

只需使用onclickonsubmit事件處理程序以老式方式添加它。 我建議使用onsubmit ,因為無需單擊按鈕即可提交表單。

由於您已經加載了腳本,因此您可以添加:

<script>
    function gtag_report_conversion(url){
        var callback = function () {
            if (typeof(url) != 'undefined') {
                window.location = url;
            }
        };
        gtag('event', 'conversion', {
                'send_to': 'AW-.....',
                'event_callback': callback
        });
        return false;
    }

    document.getElementById("your-form-id").onsubmit = function(){
        gtag_report_conversion();
    };
</script>

只需將your-form-id替換為<form>元素的id (不是您的提交按鈕)。

暫無
暫無

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

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