Alertify警告确认对话框在Ruby on Rails中无法正常工作求助
data-confirm Hey there! Let's get your AlertifyJS confirm dialog working in your Rails app. The root issue here is that Rails UJS (Unobtrusive JavaScript) uses its own default handler for the data-confirm attribute, which bypasses Alertify. Here's how to override that behavior and make Alertify take over:
Step 1: Double-Check Asset Loading
First, let's rule out basic loading issues:
- Verify your
application.jsrequire order (this is critical!)://= require jquery //= require jquery_ujs //= require modules/alertify // Add your override code AFTER requiring alertify - Check for a typo in your CSS path: you wrote
assets/stylsheets/modules/alertify.css—it should beassets/stylesheets/modules/alertify.css. Fix that if it's a mistake, otherwise your Alertify styles won't load properly. - Open your browser's developer console (F12) and look for errors like
Alertify is not defined—if you see this, your Alertify JS file isn't loading correctly. Double-check the file path and require statement spelling.
Step 2: Override Rails' Confirm Handler
Since Alertify uses asynchronous callbacks (unlike the browser's blocking native confirm), we need to hook into Rails' rails:confirm event instead of just overriding a function. Add this code to your application.js (after requiring Alertify):
// Replace Rails' default confirm with AlertifyJS $(document).on('rails:confirm', function(event, element) { // Stop the default browser confirm from firing event.preventDefault(); // Grab the confirmation message from the data-confirm attribute const confirmMessage = element.data('confirm'); // Show Alertify's custom confirm dialog Alertify.confirm(confirmMessage, function(isConfirmed) { if (isConfirmed) { // If the user confirms, trigger the original Rails action element.trigger('rails:confirmed'); } // If they cancel, do nothing—action is aborted automatically }); });
Step 3: Test the Fix
- Restart your Rails server to ensure all asset changes take effect.
- Clear your browser's cache (old asset files might be cached and cause issues).
- Click your link:
You should now see Alertify's custom confirm dialog instead of the browser's native one. Clicking "OK" will proceed with the link action, and "Cancel" will abort it.<%= link_to "Go!", new_employer_session_path, data: {confirm: "Are you sure? " } %>
Bonus: Customize Alertify (Optional)
If you want to tweak the dialog's look or behavior, set Alertify defaults before the override code:
// Example customizations Alertify.defaults.theme.ok = "btn btn-primary"; Alertify.defaults.theme.cancel = "btn btn-secondary"; Alertify.defaults.glossary.title = "Wait a Second!";
内容的提问来源于stack exchange,提问作者alfa

