首页 > 解决方案 > 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();                
    }
}),

标签: javascriptjquery

解决方案


将事件更改为 evt。

if (!isValid) 
{
    evt.preventDefault();                
}

您试图阻止的事件是来自“提交”侦听器的事件。不是全球事件。

$("#contact_form").submit( evt => { });

推荐阅读