关于JavaScript中onclick的执行顺序

huangapple go评论76阅读模式
英文:

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 -->

&lt;form action=&quot;post&quot; name=&quot;formTest&quot;&gt;
    &lt;button type=&quot;button&quot; onclick=&quot;A(B)&quot; id=&quot;test&quot;&gt;test&lt;/button&gt;
&lt;/form&gt;
&lt;script&gt;
    function A(B) {
        formTest.submit();
        B();
    }

    function B() {
            window.alert(&#39;Function B&#39;);
    }
&lt;/script&gt;

<!-- 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.

huangapple
  • 本文由 发表于 2023年5月29日 10:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354340.html
  • javascript

如何使用` :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定