简体   繁体   中英

Hoisting causing issues in jQuery

I am declaring the global variable isValid to true initially. Then when I navigate across tabs, I submit the form and upon submit, the value of isValid is changed to false . However, the first time I navigate, it alerts a value of true rather than false . For some reason, the submit function is being invoked after the alert statement. What can I do so that it is invoked before the alert statement?

var isValid = true;

$('form').on('submit', function(e)) {
    e.preventDefault();
    // rest of the code
    isValid = false;
}

$(document).on('hide.bs.tab', '.nav-pills a', function()) {
    $('form').submit();
    alert(isValid);
}

The submit handler is getting called asynchronously, so the order may be non-deterministic. You could put the alert call in your handler, or consider using something like jQuery deferred.promise() to control the flow of calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM