javascript - jQuery中不推荐使用“事件”是什么意思?
问题描述
我正在尝试使用 jQuery 验证电子邮件表单,但它不起作用,这是我认为问题所在的代码部分:
if (isValid == false) {
event.preventDefault();
}
我收到事件已弃用的消息,这是什么意思,我该如何解决?
编辑(这是整个代码):
$("#contact_form").submit( evt => {
let isValid = true;
// validate the first name entry
const firstName = $("#first_name").val().trim();
if (firstName == "") {
$("#first_name").next().text("This field is required.");
isValid = false;
} else {
$("#first_name").next().text("");
}
$("#first_name").val(firstName);
// validate the last name entry
const lastName = $("#last_name").val().trim();
if (lastName == "") {
$("#last_name").next().text("This field is required.");
isValid = false;
} else {
$("#last_name").next().text("");
}
$("#last_name").val(lastName);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
解决方案
将事件更改为 evt。
if (!isValid)
{
evt.preventDefault();
}
您试图阻止的事件是来自“提交”侦听器的事件。不是全球事件。
$("#contact_form").submit( evt => { });
推荐阅读
- java - 正确修复 Java 10 抱怨 jaxb-impl 2.3.0 非法反射访问?
- python - 如何以整数和字符串作为输入执行算术运算
- swift - Swift Core Data:删除行时更新无效
- java - PHP 返回的 JSON 看起来像 HTML 代码
- mysql - 如何构建一个包含表之间匹配计数的矩阵?
- javascript - 在本地使用 Node.js 时客户端和服务器时间不同
- python - 如何将此 SQL 转换为 Django 查询?
- r - 在数据帧的每一行上使用 apply 时避免 for 循环
- php - array_pop 函数弹出数组的两个元素
- elasticsearch - ElasticSearch:如何使用 Java High Level REST Client 跨多个字段执行搜索?