javascript - 动态加载 reCAPTCHA

标签 javascript jquery recaptcha

有几种使用 javascript 加载 reCAPTCHA 的方法,如下所示:

<html>
  <head>
    <title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type='text/javascript'>
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
    </script>
  </head>
  <body>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
  </body>
</html>

此代码在页面加载时加载验证码。我想在单击“MYBTN”时加载 reCAPTCHA。所以代码变为:

<html>
  <head>
    <title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type='text/javascript'>
$('#MYBTN').on('click',function(){
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
 });
    </script>
  </head>
  <body>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
  </body>
</html>

但是当我点击“MYBTN”并且没有加载 reCAPTCHA 时,这段代码不起作用。 请帮助我。谢谢。

最佳答案

你只需要调用loadCaptcha()

$('#MYBTN').on('click',function(){
    var captchaContainer = null;
    var loadCaptcha = function() {
      captchaContainer = grecaptcha.render('captcha_container', {
        'sitekey' : 'Your sitekey',
        'callback' : function(response) {
          console.log(response);
        }
      });
    };
    loadCaptcha(); // THIS LINE WAS MISSING
 });
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
      <div id="captcha_container"></div>
      <input type="button" id="MYBTN" value="MYBTN">
      <script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>

关于javascript - 动态加载 reCAPTCHA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245768/

相关文章:

javascript - 如何避免在 Javascript 的大循环中测试要添加到字符串中的元素是否存在?

javascript - 无法读取未定义的属性替换

javascript - map和reduce的主要区别

javascript - 从使用 ajax 的函数获取返回值

recaptcha - 如何在页面背景中包含 reCAPTCHA v3?

javascript - 如何在运行时向页面添加javascript代码?

javascript - 如何使用 AJAX 验证 Google Recaptcha V3 响应

javascript - Android 4.4 浏览器在数组推送方法中报告意外标识符

php - 如何从 laravel blade 中的 json 数据创建分页链接

javascript - 如何从 $.getJSON 函数返回值?