如何通过HTML按钮点击事件调用JavaScript类方法并显示输入用户名?
Got it, let's break down what's going wrong here and fix it quickly.
Your current code grabs the input's value immediately when the page loads—at that point, the user hasn't had a chance to type anything, so the name variable is just an empty string. When you create the Student instance with that empty value, calling show() later will only log that empty string.
Solution 1: Fetch the Input Value When the Button is Clicked
The simplest fix is to move the input value retrieval inside the show() method, so it grabs the current value every time the button is clicked:
Updated HTML (can stay unchanged):
<body> <input type="text" id="userName"> <button onclick="st.show()">Click</button> </body> <script src="script.js"></script>
Updated JavaScript:
class Student{ show(){ // Grab the input's current value when the method is triggered const currentName = document.getElementById('userName').value; console.log(currentName); } } // We only need to create the Student instance once const st = new Student();
Solution 2: Separate Logic with Event Listeners (Best Practice)
If you prefer to keep your HTML and JavaScript separated (a cleaner approach for larger projects), you can ditch the inline onclick and use an event listener instead:
Updated HTML:
<body> <input type="text" id="userName"> <button id="showNameBtn">Click</button> </body> <script src="script.js"></script>
Updated JavaScript:
class Student{ showUsername(){ const currentName = document.getElementById('userName').value; console.log(currentName); } } const student = new Student(); // Attach the click event listener to the button document.getElementById('showNameBtn').addEventListener('click', () => { student.showUsername(); });
Why This Works
By moving the document.getElementById('userName').value call inside the method that runs on button click, we ensure we're always getting the latest value the user has typed—not the empty value from page load.
内容的提问来源于stack exchange,提问作者Anjali Patel

