我对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=G3Y3E1YISNH1setTimeout()综上所述,正在运行myFunction,但没有预期的延迟。如果有人可以帮助我正确编写代码,我将不胜感激!谢谢。
3 回答

qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
使用现代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);
});

潇潇雨雨
TA贡献1833条经验 获得超4个赞
您必须发送一个函数才能执行一个函数。可以使用:
onsubmit="setTimeout('myFunction()', 3000)"
或使用这种方式:
onsubmit="setTimeout(function () { myFunction(); }, 3000)"
另外,如果您不提交表单,则可以尝试执行以下操作return false
:
onsubmit="setTimeout(function () { myFunction(); }, 3000); return false;"
并且请通过使用不打扰的方法addEventListener
。

PIPIONE
TA贡献1829条经验 获得超9个赞
您正在分配过程中执行该功能。卸下支架()
。实际上,您实际上需要将引用作为参数传递给函数。添加括号时,您要执行函数,然后将函数的返回值作为参数传递。
<form onsubmit="setTimeout(myFunction, 3000)">
此外,您也不应完全使用onsubmit
和内联分配。
添加回答
举报
0/150
提交
取消