英文:
About execution order of onclick in JavaScript
问题
我对JavaScript中onclick属性的执行顺序有一个问题。
我想知道为什么在表单提交后写的函数会被执行。
为什么它不是从上面运行的?
<form action="post" name="formTest">
<button type="button" onclick="A(B)" id="test">test</button>
</form>
<script>
function A(B) {
formTest.submit();
B();
}
function B() {
window.alert('Function B');
}
</script>
英文:
I have a question about the execution order of the onclick attribute in JavaScript.
I would like to know why the function written after form submission is executed.
Why is it not run from above?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<form action="post" name="formTest">
<button type="button" onclick="A(B)" id="test">test</button>
</form>
<script>
function A(B) {
formTest.submit();
B();
}
function B() {
window.alert('Function B');
}
</script>
<!-- end snippet -->
答案1
得分: 2
表单提交和 formTest.submit()
是异步的,意味着它们会被执行,但浏览器在继续执行下一行代码之前不会等待它们完成。
因为提交表单相对于触发警报来说是一个相对较长的过程(例如:您必须发送HTTP请求并从服务器接收响应),浏览器会先运行 formTest.submit()
,然后运行 alert()
,然后后台完成提交。
英文:
Form submissions, and formTest.submit()
, are asynchronous, meaning they are executed but the browser doesn't wait for them to finish before moving on to the next line of code.
Because submitting a form is a relatively long process compared to firing an alert (ie: you have to make a HTTP request and receive a response from the server) the browser runs formTest.submit()
, runs alert()
, then the submission completes from the background.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论