按钮onclick绑定的confirm弹窗不弹出的原因排查
Let's break down why your confirm popup isn't appearing and fix the redirect logic along the way:
1. The top culprit: Function loading order
If your <script> tag is placed after the button in your HTML, when a user clicks the button, the ewAttestConfirm function hasn't been defined yet. Browsers parse HTML top-to-bottom, so the function needs to exist before the button tries to call it.
Fix: Move your <script> tag to the <head> of your document, or place it immediately before the button in the body. Here's how that looks:
<script> function ewAttestConfirm(idx) { var r = confirm("Click OK to attest that you viewed this entire program."); if (r == true) { window.location.assign(`https://example.com/ewAttestToHoursAndRedirectToCert/?idx=${idx}`); } } </script> <button onclick="ewAttestConfirm('19')">Cert</button>
2. Check for browser console errors
Open your browser's developer tools (press F12 or Ctrl+Shift+I) and switch to the Console tab. If you see an error like ewAttestConfirm is not defined, that confirms the loading order issue above. Any other errors here will point you to additional problems to fix.
3. Fix the redirect URL (your parameter isn't being passed correctly)
In your original code, idx=idx in the URL will literally pass the string "idx" instead of the actual value from the function parameter. You need to inject the variable properly:
- Use template literals (cleanest approach):
https://example.com/ewAttestToHoursAndRedirectToCert/?idx=${idx} - Or string concatenation:
https://example.com/ewAttestToHoursAndRedirectToCert/?idx=' + idx
4. Addressing the line break issue with window.location.assign
Most code editors won't block valid line breaks in JavaScript. If yours is complaining, it's likely a linter setting or an unclosed syntax block nearby. Wrapping the redirect in curly braces (as shown in the fixed code) clearly defines the scope of the if statement and should resolve the editor's complaint.
Here's the fully corrected, tested code:
<script> function ewAttestConfirm(idx) { // Display the confirmation popup var userConfirmed = confirm("Click OK to attest that you viewed this entire program."); // Redirect only if the user confirms if (userConfirmed) { window.location.assign(`https://example.com/ewAttestToHoursAndRedirectToCert/?idx=${idx}`); } } </script> <button onclick="ewAttestConfirm('19')">Cert</button>
When you click the "Cert" button now, the confirm popup should appear immediately. Clicking OK will redirect you to the URL with the correct idx=19 parameter.
内容的提问来源于stack exchange,提问作者Doug Lerner




