简体   繁体   English

如何启动 onclick function 并使其启动另一个 function?

[英]How do I launch an onclick function and make it launch another function?

I need to launch an onclick function when someone clicks a button on my site (has the id of "rum_sst_tab") and then launch another function that counts a google conversion ( gtag_report_conversion() ) I need to launch an onclick function when someone clicks a button on my site (has the id of "rum_sst_tab") and then launch another function that counts a google conversion ( gtag_report_conversion() )

I've tried some jQuery options for onclick, but they weren't working for me.我已经为 onclick 尝试了一些 jQuery 选项,但它们对我不起作用。 This is a wordpress site, and id that I'm trying to onclick on, is within a WordPress plugin - not sure if that complicates things or not with this.这是一个 wordpress 站点,我正在尝试打开 onclick 的 ID,位于 WordPress 插件中 - 不确定这是否会使事情复杂化。

document.getElementById("rum_sst_tab").onclick = gtag_report_conversion();

This is the other part of code that is connected to the gtag function:这是连接到 gtag function 的代码的另一部分:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-58161224-5"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-72452xxxx');
</script>

I'm also getting this error in the console:我也在控制台中收到此错误:

(index):1251 Uncaught TypeError: Cannot set property 'onclick' of null (索引):1251 未捕获类型错误:无法设置 null 的属性“onclick”

If you try to access the DOM before it has been parsed, getElementById() will return null, so make sure you code is called after that.如果您尝试在解析之前访问 DOM, getElementById()将返回 null,因此请确保在此之后调用您的代码。 Otherwise adding a click event is straightforward...否则添加点击事件很简单......

<!DOCTYPE html>
<html>
  <head>
    <title>so test</title>
  </head>
  <body>
    <button type="button" id="test-div">click me!</button>
    <script>
      function testFunc() {
        console.log('doing the test!');
      }
      document.getElementById('test-div').onclick = testFunc;
    </script>
  </body>
</html>

Correct way to call your function is:调用 function 的正确方法是:

document.getElementById('rum_sst_tab').onclick = 
       function(){
             gtag_report_conversion();
       }

(Look: Call a function with the submit button in HTML ) (看: 使用 HTML 中的提交按钮调用 function

Note:笔记:

It's recommended you wait 9-10 hours before checking your conversion rates.建议您等待 9-10 小时后再检查您的转化率。 This is how long it could take for Google Analytics and Google Ads to begin working together.这是 Google Analytics 和 Google Ads 开始合作可能需要多长时间。

(At the final thoughts of https://wpforms.com/how-to-track-form-submissions-as-google-adwords-conversions/ ) (在https://wpforms.com/how-to-track-form-submissions-as-google-adwords-conversions/的最终想法中)

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

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