我有一个由遗留后端代码生成的表单,由于各种原因,我无法更改。表单是简单的 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()
,因为这些是由我无法更改的遗留后端代码生成的?