如何在Bootstrap完成指定函数后,运行jQuery自定义函数?
Hey there! Let's get that form-hiding-on-modal-close issue sorted out for your last-minute project—this is straightforward once you use Bootstrap's built-in modal events, no need to manually track every close trigger.
Here's how to do it:
Bootstrap modals fire a specific event when they've fully closed (including finishing their fade animation) called hidden.bs.modal. We can hook into this event to run our form-hiding logic.
Step 1: Add the event listener
Assuming your modal has an ID of successModal and your form uses the ID submitForm, add this jQuery code:
// Listen for when the modal finishes closing $('#successModal').on('hidden.bs.modal', function() { // Hide the form once the modal is gone $('#submitForm').hide(); });
Full Working Example (with your existing submit logic)
If your current code to show the modal on submit looks like this:
$('#submitBtn').click(function(e) { e.preventDefault(); // Stop the form from submitting normally (if needed) $('#successModal').modal('show'); // Pop up the success message });
Just combine it with the event listener inside a document.ready wrapper to make sure everything loads properly:
$(document).ready(function() { // Trigger modal on submit button click $('#submitBtn').click(function(e) { e.preventDefault(); $('#successModal').modal('show'); }); // Hide form after modal closes completely $('#successModal').on('hidden.bs.modal', function() { $('#submitForm').hide(); // Optional: Use fadeOut() for a smoother effect instead // $('#submitForm').fadeOut(); }); });
Why this works so well:
- The
hidden.bs.modalevent covers all ways to close the modal: clicking the "×" button, clicking outside the modal, pressing ESC, or even callingmodal('hide')via code. You don't have to write separate handlers for each case! - Using jQuery's
hide()instantly hides the form, but if you want a nicer transition, swap it out forfadeOut()as noted in the comment.
That should wrap up your final requirement—good luck with your project deadline!
内容的提问来源于stack exchange,提问作者Kris Hale

