如何让onClick()调用外部index.js文件处理表单验证逻辑?
Got it, let's fix this issue for you. The problem with your current setup is twofold: your JS code runs immediately when the page loads (before the user has a chance to enter anything, and without any connection to the button click), plus you're using the wrong property to get input values. Here's how to adjust things to use external JS exclusively:
Step 1: Update Your index.js File
We need to wait for the DOM to fully load, then bind a click event listener to the button, and run your validation logic only when the button is clicked. Replace your current index.js with this:
// Wait until all DOM elements are loaded before accessing them document.addEventListener('DOMContentLoaded', function() { // Grab the button element const submitButton = document.querySelector('button'); // Add a click event listener to the button submitButton.addEventListener('click', function() { // Get the actual input values (use .value, not nodeValue!) const emailInput = document.getElementById('email').value; const passwordInput = document.getElementById('pass').value; // Run your validation logic if (emailInput === passwordInput) { alert("You are allowed"); } else { alert("Email and password don't match"); } }); });
Step 2: No Changes Needed to index.html
Your existing HTML is fine—we're using event listeners instead of inline onClick attributes, which keeps your JS entirely in the external file, just like you wanted.
Why This Works:
DOMContentLoadedensures we don't try to access elements before they exist on the page.addEventListenerbinds the click action to the button without cluttering your HTML with inline JS..valueis the correct way to retrieve text from input fields—nodeValueis for getting content from text nodes, not form inputs.
A quick note: In a real-world scenario, validating that email equals password isn't a practical check, but I kept your original logic intact since that's what you provided.
内容的提问来源于stack exchange,提问作者user14373544

