Noty.js v3.1.4调用n.close()无法关闭模态框的问题求助
Let’s break down the issues in your code and fix them step by step:
1. Incorrect modal Option Type
You’ve set modal: 'true' (a string), but Noty v3 expects a boolean value for the modal option. Even though JavaScript treats non-empty strings as truthy, Noty’s internal logic relies on strict type checks for modal handling. This mismatch can cause the modal backdrop to stick around even when the Noty instance reports itself as closed.
Fix: Update the modal option to use a boolean:
modal: true,
2. Using External Instance Variable Instead of this in Button Callback
In your "No" button callback, you’re using the global n variable to call close(). While this might work in simple cases, the more reliable approach is to use this inside the button callback—this directly refers to the active Noty instance, eliminating any potential scope or reference issues.
Fix: Adjust both button callbacks to use this:
buttons: [ Noty.button("Yes", "btn btn-primary", function () { location.reload(); this.close(); // Optional (reload refreshes the page), but follows best practice }), Noty.button("No", "btn btn-primary ml-3", function () { checkAvailability = true; this.close(); // Use `this` to target the current modal instance }) ],
3. Bonus: Prevent Future Instance Reusability Issues
A single Noty instance can only be displayed once. If your availability check runs again after closing the modal and the site is still accessible, calling n.show() on a closed instance will cause unexpected behavior. To avoid this, create a new Noty instance each time you need to show the modal instead of reusing the same one.
Example of Dynamic Instance Creation:
// Remove the pre-defined `n` variable function showAvailabilityModal() { new Noty({ text: "Website under construction", type: 'alert', layout: 'center', theme: 'bootstrap-v4', modal: true, buttons: [ Noty.button("Yes", "btn btn-primary", function () { location.reload(); }), Noty.button("No", "btn btn-primary ml-3", function () { checkAvailability = true; this.close(); }) ], animation: { open: 'animated fadeIn faster', close: 'animated fadeOut faster' } }).show(); } // Update your AJAX success callback to use the new function success : function(){ checkAvailability = false; timeout = 30000; showAvailabilityModal(); // Create and display a fresh modal instance },
After applying these fixes, your "No" button will properly close the modal, and the backdrop will be removed as expected.
内容的提问来源于stack exchange,提问作者CribAd

