javascript - 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 但没有预期的延迟。如果有人可以帮助我正确地编写代码,我将不胜感激!谢谢。
解决方案
使用现代 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);
});
推荐阅读
- powershell - 连接应用程序 id 和密码时使用 powershell 处理 o365 邮箱中的电子邮件
- flutter - Flutter:如何显示来自同一个函数的多条数据
- android - R8 在构建时静默崩溃
- javascript - 使用类类型定义创建普通对象
- html - 你能帮我用这个简单的html代码吗?
- excel - 如何使用 Excel VBA 将另存为 HTML 电子邮件?
- ruby-on-rails - 如何以编程方式获取 Ruby 的标准库(或系统 gem)路径?
- xamarin - Xamarin:使用 Community TabView 显示两个页面实际上并没有正确初始化页面
- button - 选项道具中缺少材料表导出按钮
- python - python请求json参数未转换为URL参数