首页 > 解决方案 > JavaScript setTimeout() 函数不适用于“onsubmit”表单属性

问题描述

我对 JavaScript 很陌生,如果我遗漏了一些明显的东西,我深表歉意。

我试图在提交表单时显示一个隐藏的 div,但不是立即显示它,而是需要稍微延迟(例如 3 秒)出现。

我曾尝试在“onsubmit”属性上使用 setTimeout() 函数,但隐藏的 div 会立即出现并且不会延迟。

这是一个最小的例子:

<!DOCTYPE html>
<html>

<body>

  <p>When you submit the form, a function is triggered which alerts some text.</p>

  <form action="/action_page.php" onsubmit="setTimeout(myFunction(), 3000)">
    Enter name: <input type="text" name="fname">
    <input type="submit" value="Submit">
  </form>

  <div id="message" style="display: none">Loading...</div>

  <script>
    function myFunction() {
      document.getElementById("message").style.display = "block"
    }
  </script>

</body>

</html>

也可以在这里找到: https ://www.w3schools.com/code/tryit.asp?filename=G3Y3E1YISNH1

总而言之,setTimeout()正在运行 myFunction 但没有预期的延迟。如果有人可以帮助我正确地编写代码,我将不胜感激!谢谢。

标签: javascripthtmlsettimeoutonsubmit

解决方案


使用现代 JS 约定。在 JS 端,而不是 HTML 端,找到你的表单,并使用事件监听:

let form = ... // there are many easy ways to get this element

form.addEventListener("submit", evt => {
  // don't actually submit this form to its associated URL:
  evt.preventDefault();
  // and schedule the timeout
  setTimeout(myFunction, 3000);
});

推荐阅读