我有以下代码。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sleep( lf_ms ) {
return new Promise( resolve => setTimeout( resolve, lf_ms ) );
}
async function check_form() {
alert( 'Test 1' );
await sleep( 1000 );
alert( 'Test 2' );
return false;
}
</script>
</head>
<body>
<form name="myform" method="post" action="test.htm" onsubmit="return check_form();">
<input type="text" name="city"><br>
<br>
<a href="javascript:check_form();">check the method call via link</a><br>
<br>
<button type="submit">check the method call via submit button</button><br>
<br>
</form>
</body>
</html>
我想将功能check_form()睡眠1秒钟。
如果单击链接,将显示“测试1”和“测试2”。如果单击提交按钮,则仅显示“测试1”。我在这里做错了什么?
我的问题与使用Promise使用Submit()提交表单不同。因为未使用javascript事件处理程序onsubmit。
return check_form()
不会false
如您所想的那样返回。异步函数总是返回一个隐式的Promise
,因此,您的表单仍然被提交。之所以alert
显示第一个,是因为到目前为止,它仍然是同步的。之后的所有内容都sleep
将安排在以后的时间,表单提交将不等待该时间。
要解决它,您可以调用该函数,然后返回false
。
function sleep(lf_ms) {
return new Promise(resolve => setTimeout(resolve, lf_ms));
}
async function check_form() {
console.log('Test 1');
await sleep(1000);
console.log('Test 2');
}
<form name="myform" method="post" onsubmit="check_form(); return false;">
<input type="text" name="city"><br>
<br>
<a href="javascript:check_form();">check the method call via link</a><br>
<br>
<button type="submit">check the method call via submit button</button><br>
<br>
</form>
编辑以发表您的评论
在功能check_form中检查用户输入。如果输入无错误,则该函数返回true。如果有错误,该函数将返回false。如果发生错误,则不应调用存储在标签表单的属性操作中的页面。
您不能像这样暂停JavaScript,但是可以return false
用来停止提交,然后在验证之后通过JavaScript提交表单。
function sleep(lf_ms) {
return new Promise(resolve => setTimeout(resolve, lf_ms));
}
async function check_form(form) {
console.log('Test 1');
await sleep(1000);
console.log('Test 2');
let city = document.getElementById('city').value;
// Validation
if (form !== undefined && city.trim() !== "") {
// Validation succeeded, submit the form
form.submit();
}
}
<form name="myform" method="post" onsubmit="check_form(this); return false;">
<input type="text" id="city" name="city"><br>
<br>
<a href="javascript:check_form();">check the method call via link</a><br>
<br>
<button type="submit">check the method call via submit button</button><br>
<br>
</form>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句