JavaScript/jQuery Callback on(“submit”)

2019-09-11 18:34发布

Can someone tell me why this script doesn't work.

I want the alert for "I just submitted the form" before "The form submitted." So I used a callback but it's still jumping past the submit.

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>

2条回答
Deceive 欺骗
2楼-- · 2019-09-11 18:52

You must run your callback function within the jQuery event handler function (the second argument to on. Otherwise, callback will just execute immediately inside of formSubmit, but alert("I just submitted the form."); will only execute once the submit event occurs.

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

formSubmit( function() {
    alert("The form submitted.");
});
查看更多
Summer. ? 凉城
3楼-- · 2019-09-11 19:01

You need to call the callback after the alert, not after binding the submit handler.

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
        callback();
    });   
}
查看更多
登录 后发表回答