简体   繁体   English

Onclick 与 window.onload function

[英]Onclick with window.onload function

I've no idea if this is the right way to do what I'm trying to do (I have 0 experience with jQuery/Javascript):我不知道这是否是做我想做的事情的正确方法(我对 jQuery/Javascript 有 0 经验):

window.onload = function () {
     var Btn = document.getElementById('fmm-payment-btn');
     Btn.onclick = function () {
         gtag_report_conversion();
     }
}

The gtag_report_conversion() looks like this: gtag_report_conversion() 如下所示:

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

Basically, I'd like to make sure that the function gtag_report_conversion() is executed when users click on fmm-payment-btn (to track conversions in Google Ads).基本上,我想确保在用户点击fmm-payment-btn时执行 function gtag_report_conversion() (以跟踪 Google Ads 中的转化)。

I tried this in a slightly different way using document.getElementById("fmm-payment-btn").onclick = function() but I kept getting an error, Uncaught TypeError: Cannot set property 'onclick' of null .我使用document.getElementById("fmm-payment-btn").onclick = function()以稍微不同的方式尝试了这个,但我一直收到错误, Uncaught TypeError: Cannot set property 'onclick' of null I understand the method above should work better, but having no experience I cannot tell.我知道上面的方法应该会更好,但是没有经验我不能说。

Would appreciate any feedback.任何反馈将不胜感激。 :) :)

window.onload doesn't mean that the DOM is loaded. window.onload并不意味着 DOM 已加载。

If you want to be sure that the button is rendered you should use如果你想确保按钮被渲染,你应该使用

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
    document.getElementById("fmm-payment-btn").onclick = function(){}
    // Or
    document.getElementById("fmm-payment-btn").addEventlistener('click', function(){})
    // Or even cleaner
    document.getElementById("fmm-payment-btn").addEventlistener('click', gtag_report_conversion)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM