JavaScript/jQuery 回调 ("submit")

JavaScript/jQuery Callback on("submit")

谁能告诉我为什么这个脚本不起作用。

我想要 "I just submitted the form" 之前的警报 "The form submitted." 所以我使用了回调,但它仍然跳过了提交。

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
    });
    callback();
}

formSubmit( function() {
    alert("The form submitted.");
});

HTML

<body>
    <form>
        <input type="submit"/>
    </form>
</body>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/forTesting.js"></script>

您必须 运行 您的 callback 函数在 jQuery 事件处理函数中(on 的第二个参数)。否则,callback 将只执行立即在 formSubmit 内部,但 alert("I just submitted the form."); 只会在提交事件发生后执行。

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
        callback();
    });
}

formSubmit( function() {
    alert("The form submitted.");
});

您需要在警报之后调用回调,而不是在绑定 submit 处理程序之后。

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
        callback();
    });   
}