首页 > 解决方案 > 将表单 onsubmit 参数与 jquery 提交事件处理程序相结合

问题描述

我有一个由遗留后端代码生成的表单,由于各种原因,我无法更改。表单是简单的 HTML:

<form action="#" id="theForm" onsubmit="return check_theForm(); method="post">
  <!-- fields go here -->
</form>

提交时,使用包含“plain vanilla”javascript(即没有jQuery代码)onsubmit的函数,参数会触发以验证是否已填写所有必填字段。check_theform()换句话说,基本的东西。

我现在尝试通过添加以下内容将 reCAPTCHA V3 添加到此表单中:

$('#theForm').submit(function(event) {
  event.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      {action: 'contactForm'}).then(function(token) {
        $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
        $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
        $('#theForm').unbind('submit').submit();
      });;
  });
});

问题是表单的onsubmit参数首先触发,然后运行check_theForm(),然后$('#theForm').submit(function(event)处理程序触发,最终运行$('#theForm').unbind('submit').submit();在该点check_theForm()运行第二次。如果有表单错误,现在会显示两次。

如何在不更改表单的 HTML 代码或 的情况下防止这种重复check_theForm(),因为这些是由我无法更改的遗留后端代码生成的?

标签: jqueryformsevent-handlingonsubmitrecaptcha-v3

解决方案


当你有onsubmit="x()"你可以删除 html onsubmit 处理程序

$("#id").attr("onsubmit", null);

允许您在没有自己的事件处理程序的情况下完全控制。

在这种情况下,给出:

$("#theForm").attr("onsubmit", null);

$('#theForm').submit(function(event) {
  event.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      {action: 'contactForm'}).then(function(token) {
        $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
        $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
        if (check_theForm())
            $('#theForm').unbind('submit').submit();
      });;
  });
});

推荐阅读