jquery - 将表单 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()
,因为这些是由我无法更改的遗留后端代码生成的?
解决方案
当你有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();
});;
});
});
推荐阅读
- r - 如何以编程方式评估空 quosure?
- json - Gtmetrix 使用本机反应获取报告
- angular - Angular - 如何将角度变量绑定到 html 并显示
- android - 如何让 Firebase 在数据库的三个不同区域显示相同的 ID?
- javascript - TypeError: undefined is not an object (evaluating 'store.getState')
- image-processing - 缝合在静止相机的视野中部分可见的移动物体
- python - pyspark 数据帧的慢速过滤
- javascript - 如何使用 selectize.js 设置选择的默认选项
- amazon-athena - AWS Glue Crawler 未在架构中创建表
- python - 在 Python 中使用 SQLalchemy 连接到 AWS 中的人口普查公共数据库