繁体   English   中英

单击警报确定按钮后如何防止刷新? 返回 false 在这里不起作用

[英]How to prevent refresh after clicking the alert OK button? Return false doesn't work here

我有一个表格来更新用户的个人资料,我想在用户将密码字段留空时提醒他们。

目前,当用户将密码字段留空并提交表单时,会出现警告框。 但是在单击警报上的确定按钮后,页面会刷新,并且用户以某种方式将其密码更新为空白......

这是我的代码:

$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
  e.preventDefault();
  const updatedUser = {
    name: $("#edit-user-name").val(),
    password: $("#edit-user-password").val(),
  };
  if (!updatedUser.password) {
    alert("Password can't be empty!");
    // not working. It still refreshes the page and set the password to empty
    return false;
  } else {
    currentUser = await currentUser.updateProfile(updatedUser);
    saveUserCredentialsInLocalStorage();
    return true;
  }
}

我也尝试过e.preventDefault()但效果不佳。 请告诉我如何防止页面重新加载。 谢谢!


编辑:我将return false更改为return true并且它有效...但我在控制台中收到警告说[Violation] 'submit' handler took 1130ms jquery:5229有人可以帮我解释这里发生了什么吗? 这是新代码:

$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
  e.preventDefault();
  const updatedUser = {
    name: $("#edit-user-name").val(),
    password: $("#edit-user-password").val(),
  };
  if (!updatedUser.password) {
    alert("Password can't be empty!");
    // working now, the page doesn't refresh but receives a warning
    return true;
  } else {
    currentUser = await currentUser.updateProfile(updatedUser);
    saveUserCredentialsInLocalStorage();
    // I have to use reload() to force the page upload
    location.reload();
  }
}

您不需要从该代码返回任何内容。 e.preventDefault() 应该处理不提交 -

纯js版本

 document.getElementById("myForm").addEventListener("submit", asyncsubmit) async function asyncsubmit(e) { e.preventDefault(); if (e.target.querySelector("[name=q]").value === "") alert("Don't leave empty") else console.log(e.target.id) }
 <form id="myForm" action="https://www.google.com/search"> <input type="text" name="q"> <input type="submit" value="search"> </form>

jQuery

 $("#myForm").on("submit", asyncsubmit) async function asyncsubmit(e) { e.preventDefault(); if ($(e.target).find("[name=q]").val() ==="") alert("Don't leave empty") else console.log(e.target.id) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <form id="myForm" action="https://www.google.com/search"> <input type="text" name="q"> <input type="submit" value="search"> </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM